RSpec Rails Login Filter

2019-07-24 04:41发布

问题:

I recently switched started using rspec-rails(2.6.1) with my Rails(3.0.8) app. I'm used to Test::Unit, and I can't seem to get a filter working for my test methods. I like to keep things as DRY as possible, so I'd like to set up a filter that I can call on any test method that will login as an Authlogic user before the test method is called. I tried accomplishing this by using an RSpec filter in spec_helper.rb:

config.before(:each, :login_as_admin => true) do 
  post "/user_sessions/create", :user_session => {:username => "admin", :password => "admin"}   
end

Then I use it in the corresponding test method(in this case spec/controllers/admin_controller_spec.rb):

require 'spec_helper'

describe AdminController do  
  describe "GET index" do        
    it("gives a 200 response when visited as an admin", :login_as_admin => true) do   
      get :index
      response.code.should eq("200")
    end    
  end
end

However, I get this error when I run rspec spec:

Failures:

  1) AdminController GET index gives a 200 response when visited as an admin
     Failure/Error: Unable to find matching line from backtrace
     RuntimeError:
       @routes is nil: make sure you set it in your test's setup method.

Blech. Can I only send one HTTP request per test? I also tried stubbing out my authenticate_admin method(inside the config.before block), without any luck.

回答1:

Unfortunately, there is no way at the moment to do what you're trying to do in a globally defined before hook. The reason is that before hooks are executed in the order in which they get registered, and those declared in RSpec.configure are registered before the one that rspec-rails registers internally to set up the controller, request, response, etc.

Also, this has been reported to https://github.com/rspec/rspec-rails/issues/391.



回答2:

You should use shulda's macrons. To use shoulda modify your spec_helper.rb

RSpec.configure do |config|
  config.include Clearance::Shoulda::Helpers
end

And then can setup filter in controller spec like

require 'spec_helper'

describe AdminController do  
  fixture :users

  before(:each) do
    sign_in_as users(:your_user)
  end
  describe "GET index" do        
    it("gives a 200 response when visited as an admin", :login_as_admin => true) do   
      get :index
      response.code.should eq("200")
    end    
  end
end