3

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

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):

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时出现此错误:

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 块内),但没有任何运气。

4

2 回答 2

4

before不幸的是,目前没有办法在全局定义的钩子中做你想做的事情。原因是before钩子是按照它们注册的顺序执行的,并且声明的钩子在内部注册以设置控制器、请求、响应等的钩子RSpec.configure之前注册。rspec-rails

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

于 2011-06-18T12:18:07.963 回答
-1

您应该使用 shulda 的宏。要使用应该修改您的 spec_helper.rb

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

然后可以在控制器规范中设置过滤器,例如

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
于 2011-06-18T07:37:52.090 回答