我正在尝试编写一些 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) 当不存在 session 信息时,用户访问主页路由到主页路由/到 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 当不存在 session 信息时
通过谷歌搜索,我猜测 rspec/capybara 处理条件路由的方式可能存在问题。
有没有用 rspec 和 capybara 测试路线的约束?
最佳答案
在过去的几天里,这让我发疯了,我在同事的帮助下找到了解决方案。
使用命名路由约束时,如 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
请注意,这要求您具有命名约束,这可能不适用于您的情况。
关于ruby-on-rails - Rspec 测试条件路由约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7600694/