【问题标题】:Rspec testing conditional routing constraintsRspec 测试条件路由约束
【发布时间】:2011-09-29 16:52:57
【问题描述】:

我正在尝试编写一些 rspec 集成测试来测试我的条件路由是否正确路由,但我遇到了很多问题。

在 routes.rb 中:

root :to => "error#ie6", :constraints => {:user_agent => /MSIE 6/}
root :to => "protocol_sets#index", :constraints => UserRoleConstraint.new(/doctor/i)
root :to => "refill_requests#create", :constraints => UserRoleConstraint.new(/member/i)
root :to => "refill_requests#create", :constraints => {:subdomain => "demo"}
root :to => "site#index"

在 spec/requests/homepage_routing_spec.rb 中

require 'spec_helper'

describe "User Visits Homepage" do
  describe "Routings to homepage" do
    it "routes / to site#index when no session information exists" do
      visit root_path      
    end
  end
end

我在尝试运行测试时收到以下错误。

失败: 1) 当不存在会话信息时,用户访问主页路由到主页路由/到 site#index 失败/错误:访问 root_path 无方法错误: nil:NilClass 的未定义方法“匹配” # :10:在“同步”中 # ./spec/requests/homepage_routings_spec.rb:6:in `block (3 levels) in ' 在 0.08088 秒内完成 1个例子,1个失败 失败的例子: rspec ./spec/requests/homepage_routings_spec.rb:5 # 用户访问主页路由到主页路由/到站点#index 当不存在会话信息时

通过谷歌搜索,我猜测 rspec/capybara 处理条件路由的方式可能存在问题。

有没有用 rspec 和 capybara 测试路由的约束?

【问题讨论】:

    标签: ruby-on-rails rspec routing capybara


    【解决方案1】:

    在过去的几天里,这让我发疯了,我在同事的帮助下找到了解决方案。

    当使用命名路由约束时,例如示例中的UserRoleConstraint,我实际上将约束的matches? 方法存根到需要它的规范中,即:

    describe 'routing' do
      context 'w/o route constraint' do 
        before do
          allow(UserRoleConstraint).to receive(:matches?).and_return { false }
        end
    
        # tests without the route constraint
      end
      context 'w/ route constraint' do 
        before do
          allow(UserRoleConstraint).to receive(:matches?).and_return { true }
        end
      end
    
      # tests with the route constraint
    end
    

    请注意,这要求您具有命名约束,这可能不适用于您的情况。

    【讨论】:

    • 谢谢。您现在找到更好的解决方案了吗?
    • 很遗憾,没有。
    • 我认为这实际上应该是allow_any_instance_of(UserRoleConstraint).to receive(:matches?).and_return { true }
    【解决方案2】:

    对于协议约束,您可以指定一个带有虚拟域的完整 url。见this answer

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2013-07-13
      • 2014-01-14
      相关资源
      最近更新 更多