title: Testing Rail's route's :constraints lambda with RSpec 2
body: <p><strong>Question</strong>:</p>
  
  <p>How do you setup/mock a rspec routing test to look more like a production rack environment?</p>
  
  <p>Bonus points for being able call a controller's authentication function first (eg ApplicationController.authenticate_user to set the session[:current_user_id]</p>
  
  <p><strong>Details</strong>:</p>
  
  <p>I am using route :constraints to have www.example.com/ route to two different controllers &amp; views depending on if the user is logged in or not.</p>
  
  <pre><code>root :to =&gt; 'intentions#latest', :constraints =&gt; lambda {|r| r.env['rack.session'].has_key?(:current_user_id) }
  root :to =&gt; 'welcome#index'
  </code></pre>
  
  <p>I wanted to make sure that this bit of fragile routing has a proper test around it. The cukes are testing it but I wanted to do a bit deeper of testing, specifically as I messed up the :current_user_id and the cukes did not catch that. For example I fat fingered :current_user_id in my ApplicationController's authenticate_user() method. Would love to call that in the before(:each) and make sure I am setting the correct session key.</p>
  
  <p>So I created a file called /spec/routing/auth_routing_spec.rb and tried to follow the guide at <a href="http://relishapp.com/rspec/rspec-rails/v/2-6-rc/dir/routing-specs" rel="nofollow">http://relishapp.com/rspec/rspec-rails/v/2-6-rc/dir/routing-specs</a>. I created the following spec:</p>
  
  <pre><code>it "/ should send me to home page" do
    get('/').should route_to(:controller =&gt; :index)
  end
  </code></pre>
  
  <p>When I run the spec I run into this error on the route that has the :constraint. I am assuming that env['rack.session'] does not exists. I tried to mock the request object out via <code>Rails.application.call(Rack::MockRequest.env_for('/'))</code> but that did not help out.</p>
  
  <pre><code>Failure/Error: get('/').should route_to(:controller =&gt; :index)
  NoMethodError:
    undefined method `has_key?' for nil:NilClass
  </code></pre>
  
  <p><hr />
  Boring app details</p>
  
  <p><code>rake about</code> yields</p>
  
  <pre><code>Ruby version              1.9.2 (x86_64-darwin10.6.0)
  RubyGems version          1.6.2
  Rack version              1.2
  Rails version             3.0.7
  Active Record version     3.0.7
  Action Pack version       3.0.7
  Active Resource version   3.0.7
  Action Mailer version     3.0.7
  Active Support version    3.0.7
  </code></pre>
  
  <p><code>grep rspec gemfile.info</code> yields</p>
  
  <pre><code>remote: git://github.com/rspec/rspec-rails.git
    rspec-rails (2.6.0.rc6)
      rspec (= 2.6.0.rc6)
    rspec (2.6.0.rc6)
      rspec-core (= 2.6.0.rc6)
      rspec-expectations (= 2.6.0.rc6)
      rspec-mocks (= 2.6.0.rc6)
    rspec-core (2.6.0.rc6)
    rspec-expectations (2.6.0.rc6)
    rspec-mocks (2.6.0.rc6)
  rspec-rails!
  </code></pre>