RSpec-Rails (基礎篇)(6): 撰寫Routing測試
首先在config/routes.rb
檔案中新增root
和一個自訂的action。
resources :posts do
collection do
get :last_post
end
end
root to: "posts#index"
接下來到app/controllers/posts_controller.rb
當中建立該action。
def last_post
@post = Post.last
end
接下來即可撰寫測試!
spec/routes/posts_spec.rb
require 'rails_helper'
RSpec.describe "posts", :type => :routing do
it "#index" do
expect(:get => "/posts").to route_to("posts#index")
# :controller => "posts",
# :action => "index"
# )
end
it "#show" do
expect(:get => "/posts/1").to route_to(
:controller => "posts",
:action => "show",
:id => "1"
)
end
it "#create" do
expect(:post => "/posts").to route_to(
:controller => "posts",
:action => "create"
)
end
it "#last_post" do
expect(:get => "/posts/last_post").to route_to(
:controller => "posts",
:action => "last_post"
)
end
it "root" do
expect(:get => "/").to route_to(
:controller => "posts",
:action => "index"
)
end
end