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

然而,一项测试失败:

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 回答