Rspec测试条件路由约束

3

我将尝试编写一些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时不存在会话信息 Failure/Error: visit root_path NoMethodError: NilClass的未定义方法'match' #: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 # User Visits Homepage Routings to homepage routes / to site#index when no session information exists
从谷歌搜索来看,我猜测 rspec/capybara 处理条件路由可能存在问题。
是否有办法使用 rspec 和 capybara 测试路由上的约束?
2个回答

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

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

谢谢你。你现在找到更好的解决方案了吗? - Hendrik
很遗憾,不行。 - Florian
我认为应该这样写:allow_any_instance_of(UserRoleConstraint).to receive(:matches?).and_return { true } - dkniffin

0

对于协议限制,您可以只指定一个带有虚拟域名的完整URL。请参见此答案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接