Rspec测试条件路由约束

时间:2011-09-29 16:52:57

标签: ruby-on-rails rspec routing capybara

我正在尝试编写一些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

当我尝试运行测试时出现以下错误。

Failures:

  1) User Visits Homepage Routings to homepage routes / to site#index when no session information exists
     Failure/Error: visit root_path
     NoMethodError:
       undefined method `match' for nil:NilClass
     # :10:in `synchronize'
     # ./spec/requests/homepage_routings_spec.rb:6:in `block (3 levels) in '

Finished in 0.08088 seconds
1 example, 1 failure

Failed examples:

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 个答案:

答案 0 :(得分:1)

由于这让我在最后几天疯狂,我在同事的帮助下找到了解决方案。

当使用命名路由约束时,例如示例中的re.compile(r'^\d{1,3}(?:,?\d{3})*$') ,我实际上将约束的UserRoleConstraint方法用于需要它的规范,即:

matches?

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

答案 1 :(得分:0)

对于协议约束,您只需使用虚拟域指定整个URL即可。请参阅this answer