Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec testing conditional routing constraints

I'm trying to write some rspec integration tests to test that my conditional routes are routing correctly, but I'm getting a bunch of problems.

In 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"

In 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

I get the following error when I try to run the test.

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

From Googling around I'm guessing there may be a problem with how rspec/capybara handle conditional routes.

Is there anyway to test constraints on routes with rspec and capybara?

like image 443
incomethax Avatar asked Mar 27 '26 15:03

incomethax


1 Answers

As this drove me nuts over the last days, I found the solution with the help of a colleague.

When using named route constraints, like UserRoleConstraint in the example, I resorted to actually stubbing the matches? method of the constraint int he specs that needed it, i.e.:

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

Note that this requires you to have named constraints, which might not apply to your case.

like image 65
Florian Avatar answered Mar 31 '26 04:03

Florian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!