2

でアクセスできるアクションは 2 つだけProductsControllerです。

# /config/routes.rb
RailsApp::Application.routes.draw do
  resources :products, only: [:index, :show]
end

それに応じてテストが設定されます。

# /spec/controllers/products_controller_spec.rb
require 'spec_helper'

describe ProductsController do

  before do
    @product = Product.gen
  end

  describe "GET index" do
    it "renders the index template" do
      get :index
      expect(response.status).to eq(200)
      expect(response).to render_template(:index)
    end
  end

  describe "GET show" do
    it "renders the show template" do
      get :show, id: @product.id
      expect(response.status).to eq(200)
      expect(response).to render_template(:show)
    end
  end

end

他のCRUD アクションにアクセスできないことをどのようにテストしますか? これは将来変更される可能性があるため、テストにより、構成の変更が確実に認識されるようになります。テストケースをカバーする有望なマッチャー
を見つけました。be_routable


コントローラーのアクションをテストするタイミングと理由について説明している Dave Newton によるこの投稿をお勧めします。

4

1 に答える 1

3

これが私が思いついたものです:

context "as any user" do
  describe "not routable actions" do
    it "rejects routing for :new" do
      expect(get: "/products/new").not_to be_routable
    end
    it "rejects routing for :create" do
      expect(post: "/products").not_to be_routable
    end
    it "rejects routing for :edit" do
      expect(get: "/products/#{@product.id}/edit").not_to be_routable
    end
    it "rejects routing for :update" do
      expect(put: "/products/#{@product.id}").not_to be_routable
    end
    it "rejects routing for :destroy" do
      expect(delete: "/products/#{@product.id}").not_to be_routable
    end
  end
end

ただし、1 つのテストは失敗します。

Failure/Error: expect(get: "/products/new").not_to be_routable
  expected {:get=>"/products/new"} not to be routable, 
  but it routes to {:action=>"show", :controller=>"products", :id=>"new"}

存在しないルートをテストするためにまったく異なるアプローチに従う場合は、自由に独自のソリューションを追加してください。

于 2013-08-21T13:43:11.127 に答える