0

我都混在一起試圖瞭解這裏發生了什麼:
我在User工廠使用Devise.friendly_tokenDevise.friendly_token始終返回相同的散列

FactoryGirl.define do 
    factory :user do 
    email "[email protected]" 
    password "secret" 
    authentication_token Devise.friendly_token 
    end 
end 

在某些測試中,我使用出廠如下:

require 'spec_helper' 

describe SessionsController do 

    before do 
    @user = User.gen! 
    puts "Token = #{@user.authentication_token}" # <--- debugging output 
    end 

    describe "#create" do 
    context "when sending ..." do 
     it "renders a json hash ..." do 
     api_sign_in @user 
     expect(last_response.status).to eq(201) 
     end 
    end 

    context "when sending ..." do 
     it "renders a json hash ..." do 
     user = User.gen!(email: "[email protected]") 
     puts "Token2 = #{user.authentication_token}" # <--- debugging output 
     api_sign_in user 
     expect(last_response.status).to eq(422) 
     end 
    end 
    end 

    describe "#destroy" do 
    context "when sending ..." do 
     it "renders a json hash ..." do 
     api_sign_out @user 
     expect(last_response.status).to eq(200) 
     end 
    end 
    end 

end 

調試輸出顯示令牌是在每次調用的相同的散列。 奇怪!當我在控制檯中測試Devise.friendly_token時,它會在每次執行時生成一個隨機哈希。這就是我期望看到的implementation

我想有一個主要的設計問題...請幫我。

回答

3

這條線:

authentication_token Devise.friendly_token 

將調用Devise.friendly_token只有一次出廠的時候被初始化。你想要

authentication_token { Devise.friendly_token } 

它將評估塊,每次由FactoryGirl創建一個對象。

+1

再次感謝,它在規格中工作正常。當我在'User'模型中使用'Devise.friendly_token'時,我怎麼沒有這樣做? – JJD

+0

我不確定你的意思。你如何在'User'模型中使用'Devise.friendly_token'? –

相關問題