2011-06-18 78 views
2

我最近開始使用rspec-rails(2.6.1)開始使用我的Rails(3.0.8)應用程序。我習慣於Test :: Unit,並且我似乎無法獲得適用於我的測試方法的篩選器。我喜歡儘可能保持DRY,所以我想建立一個過濾器,我可以調用任何測試方法,在調用測試方法之前,它將以Authlogic用戶身份登錄。RSpec Rails登錄過濾器

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

然後我用它在相應的測試方法(在這種情況下,規格/控制器/ 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 

但是我試圖通過在spec_helper.rb使用RSpec filter實現這一

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. 

布萊什:,當我運行rspec的規範我得到這個錯誤。我只能發送一個HTTP請求每個測試?我也嘗試刷出我的authenticate_admin方法(在config.before塊內),沒有任何運氣。

回答

3

不幸的是,有沒有辦法在此刻做你想要做什麼一個全局定義的before掛鉤。其原因是,before鉤在它們獲得註冊的順序執行,和那些在RSpec.configure聲明的一個在內部rspec-rails寄存器來設置控制器,請求,響應之前被登記等

此外,這已報告至https://github.com/rspec/rspec-rails/issues/391

+1

感謝您的信息,大衛。我很高興看到它已被報道。另外,感謝您在RSpec上的工作,它確實是一個方便的測試框架。 – dhulihan

-1

您應該使用shulda的macrons。要使用早該修改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 
+0

這不會解決OP正試圖解決的問題,因爲'sign_in_as'需要工作的位(控制器等)不會在RSpec.configure中定義的'before'鉤子之前設置'。 –