RSpec Rails 登录过滤器 [英] RSpec Rails Login Filter

查看:52
本文介绍了RSpec Rails 登录过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始在我的 Rails(3.0.8) 应用程序中使用 rspec-rails(2.6.1).我习惯于 Test::Unit,我似乎无法让过滤器为我的测试方法工作.我喜欢让事情尽可能保持干燥,所以我想设置一个过滤器,我可以在调用测试方法之前以 Authlogic 用户身份登录的任何测试方法上调用该过滤器.我尝试通过使用 RSpec 过滤器来完成此操作在 spec_helper.rb 中:

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

然后我在相应的测试方法中使用它(在本例中为spec/controllers/admin_controller_spec.rb):

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

但是,当我运行 rspec spec 时出现此错误:

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.

布莱克.我可以每次测试只发送一个 HTTP 请求吗?我还尝试删除我的 authenticate_admin 方法(在 config.before 块内),但没有任何运气.

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.

推荐答案

不幸的是,目前无法在全局定义的 before 钩子中执行您想要执行的操作.原因是 before 钩子是按照它们注册的顺序执行的,而那些在 RSpec.configure 中声明的钩子是在 rspec-rails 之前注册的 内部注册以设置控制器、请求、响应等.

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.

此外,这已报告给 https://github.com/rspec/rspec-rails/issues/391.

这篇关于RSpec Rails 登录过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆