2013-07-19 29 views
0

我實際上是使用RSpec編寫測試。以下代碼在spec/requests/tasks_spec.rb問題RSpec和FactoryGirl(避免代碼重複)

 

require 'spec_helper' 

describe "Tasks" do 

    env_headers = {'HTTP_ACCEPT' => Mime::JSON, "devise.mapping" => Devise.mappings[:user] } 

    describe "GET /tasks" do 
    context "with valid credentials" do 
     user = FactoryGirl.build(:user) 
     authorization_header = ActionController::HttpAuthentication::Basic.encode_credentials(user.authentication_token, nil) 
     env_headers['HTTP_AUTHORIZATION'] = authorization_header 

     it "should succeed" do 
     get '/tasks', nil, env_headers 
     response.status.should eq(200) 
     end 
    end 

    context "with invalid credentials" do 
     authorization_header = ActionController::HttpAuthentication::Basic.encode_credentials("123456", nil) 
     env_headers['HTTP_AUTHORIZATION'] = authorization_header 

     it "should fail" do 
     get '/tasks', nil, env_headers 
     response.status.should eq(401) 
     end 
    end 

    end 
end 
 

因爲我不是隻打算只對GET測試(但PUT,DELETE等),我想,以避免有關用戶實例化代碼的重複。如果我實際上將user = FactoryGirl.build(:user)移到了上下文之外,由於範圍問題,我將無法訪問user變量。

  • 我想知道是否有在RSpec的一個最佳實踐,以實際 爲每個背景下,這個用戶可重複使用。

  • 多,但可選的,如果我能做到只對特定 環境使用,如(對我來說):context "with valid credentials" (因爲我不需要爲我的with invalid credentials 上下文中的用戶)。

UPDATE:

通過使用讓我仍然得到一個範圍的問題,這是因爲一個愚蠢的錯誤。我正在請求一個在我的塊之外的用戶。下面的代碼是確定:

 

describe "Tasks" do 

    let(:user) { FactoryGirl.build(:user) } 

    describe "GET /tasks" do 
    context "with valid credentials" do 

     it "should succeed" do 
     authorization_header = ActionController::HttpAuthentication::Basic.encode_credentials(user.authentication_token, nil) 
     env_headers['HTTP_AUTHORIZATION'] = authorization_header 

     get '/tasks', nil, env_headers 
     response.status.should eq(200) 
     end 
    end 
 

回答

0

你可以把下面,一旦你的範圍之外:

describe "Tasks" do 

    let(:user) { FactoryGirl.build(:user) } 

    # your tests 

let是懶加載,這意味着它在每次只要叫你的規範的時間進行評估當做類似user.a_method的事情時,或者只需致電user

通過添加「!」可以指定RSpec直接評估let

let!(:foo) { 'foo' } # will be evaluated right away 
+0

你好皮埃爾 - 路易斯, 是的,我知道,這是我期待的行爲,因爲我繼續這樣,我的控制器的規格。但是在我的請求規範中,這裏的問題是我要求在「it」塊之外的用戶。當然在這種情況下用戶沒有定義,多麼愚蠢的錯誤! )。 無論如何感謝您的幫助!我會接受你的回答。 – ethd