RSpec-Rails (基礎篇)(6): 撰寫Routing測試


RSpec-Rails教學(基礎篇)全部內容

首先在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