RSpec Rails Login Filter

限于喜欢 提交于 2020-01-04 14:14:33

问题


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


来源:https://stackoverflow.com/questions/6394414/rspec-rails-login-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!