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 actions 不可访问?这可能会在将来发生变化,因此测试将确保注意到任何配置更改
我发现be_routable
matcher看起来很有希望覆盖测试用例。
我推荐这个post by Dave Newton which describes when and why to test controller actions。
答案 0 :(得分:2)
以下是我提出的建议:
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
但是一次测试失败了:
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"}
如果您采用完全不同的方法来测试不存在的路线,请随意添加自己的解决方案。