如何测试一个不存在的控制器操作?(How to test a controller action t

2019-10-18 12:37发布

只有两个动作在访问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匹配它看起来很有希望覆盖测试用例。


我建议这个职位由戴维·牛顿描述何时以及为什么给测试控制器的动作 。

Answer 1:

以下是我想出了:

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"}

请随时免费,如果你遵循一个完全不同的方法来测试不存在的路线来添加自己的解决方案。



文章来源: How to test a controller action that does not exist?