2011-09-29 115 views
3

我想寫一些rspec集成測試來測試我的條件路由路由是否正確,但我遇到了一堆問題。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" 

在規格/請求/ 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和水豚的路線限制?

回答

0

對於協議約束,您可以指定一個完整的URL與虛擬域。見this answer

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 

注意,這需要你有命名約束,這可能不適用於你的情況。

+0

謝謝你。現在你有沒有找到更好的解決方案? – Hendrik

+0

不幸的是,沒有。 – Florian