ruby-on-rails - 无需通过路由即可测试 Controller

标签 ruby-on-rails testing rspec controllers

我正在尝试单独测试我的 Controller 的 Action 链。具体来说,我想确保我想要的行为适用于我 Controller 的所有操作。例如,测试我的所有操作都需要身份验证:

context "when not authenticated" do

  # single case
  describe "GET index" do
    it "responds with 401" do
      get :index
      response.code.should be(401)
    end
  end

  # all of them...
  described_class.action_methods.each do |action|
    ['get', 'put', 'post', 'delete', 'patch'].each do |verb|
      describe "#{verb.upcase} #{action}" do
        it "responds with 401" do
          send verb, action
          response.code.should == "401"
        end
      end
    end   
  end

end

我希望这能奏效,但没有奏效。我得到了一些 ActionController::RoutingErrors。这是因为我的一些路由需要参数,而在某些情况下我没有提供它们(比如当我调用 post :create 时)。我明白了。但我不明白的是:为什么这很重要!?

对于这些测试,路由是一个单独的问题。我关心我的操作链,而不是我的请求(这就是我拥有 routing specsrequest specs 的原因)。在这个级别上,我不需要担心我的路线限制。

所以我的问题是:有没有一种方法可以在不模拟请求的情况下仅测试操作链?

编辑:一些研究

看起来路由正在 TestCase#process 中运行.有这个必要吗?

最佳答案

一种解决方法是放宽路由引擎的约束。这不会绕过路由,但确实可以更轻松地进行测试。

在您的规范中添加如下内容:

before(:all) do
  Rails.application.routes.draw { match ':controller(/:action)' }
end
after(:all) do
  Rails.application.reload_routes!
end

虽然严格来说不是问题的答案,但它可能是一个足够好的解决方法。

关于ruby-on-rails - 无需通过路由即可测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15414531/

相关文章:

javascript - 如何从 Rails Assets 管道中的不同文件调用 JS 函数

ruby-on-rails - Ruby gems 中的 "specs"是什么?

ruby-on-rails - 在 Rails 3.1 中,如何为具有 belongs_to 关联的表单创建选择列表?

javascript - 如何使用nock拦截请求而不考虑body

ruby - 为什么我的 RSpec 测试失败,但我的应用程序正常运行?

ruby-on-rails - 如何构建我的 RSpec 测试文件夹、文件和数据库?

ruby-on-rails - Rspec 3 弃用警告 : Filtering by an example_group subhash is deprecated. 使用 subhash 直接过滤

ruby-on-rails - 回形针几何类不再有效

ruby-on-rails - RSpec 是否有内置匹配器来查看字符串是一个值还是另一个值?

android - 机器人安装