【问题标题】:How to test a controller action that does not exist?如何测试一个不存在的控制器动作?
【发布时间】:2013-08-21 12:26:23
【问题描述】:

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

【问题讨论】:

  • 正如你所说,路由规范就足够了。

标签: ruby-on-rails rspec rails-routing controller-action


【解决方案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"}

如果您采用完全不同的方法来测试不存在的路线,请随意添加您自己的解决方案。

【讨论】:

  • 如果你在你的路由中添加一个 id 约束,它将起作用:constraints(id: /\d+/)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 2012-05-25
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多