2015-08-30 169 views
1

作爲主題說。看起來實施的代碼總是create一個新的記錄,而不是現有的。Rspec測試總是失敗類方法

這裏是我的RSpec的測試代碼:

describe "#from_facebook" do 
    it "return existing related user" do 
    existing_user = FactoryGirl.create(:user) 
    user_from_facebook = User.from_facebook({ uid: existing_user.uid }) 
    expect(user_from_facebook.email).to eql existing_user.email 
    end 
end 

,這裏是測試執行:

def self.from_facebook(fb_auth) 
where(provider: "facebook", uid: fb_auth[:uid]).first_or_create do |user| 
    user.email = fb_auth[:email] 
    user.password = Devise.friendly_token[0, 20] 
    end 
end 

我總是得到這樣的:

1) User#from_facebook return existing related user 
Failure/Error: expect(user_from_facebook.email).to eql existing_user.email 

    expected: "[email protected]" 
     got: nil 

    (compared using eql?) 
# ./spec/models/user_spec.rb:48:in `block (3 levels) in <top (required)>' 

這裏是控制檯結果通過put。 爲existing_user

#<User id: 105, email: "[email protected]", encrypted_password: "$2a$04$90uzEdbwfnqfUL0CDhNOH.THUbzovFyJK1OPg7VcgxL...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2015-08-30 04:12:59", updated_at: "2015-08-30 04:12:59", auth_token: "vkvm2-fLe5x1dZGbewqw", provider: nil, uid: "133290925"> 

user_from_facebook

#<User id: nil, email: nil, encrypted_password: "$2a$04$lxdBWBsXY4febfgurgHJKOdNcOMCuQQO2DHshWChnxA...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, auth_token: "", provider: "facebook", uid: "133290925"> 

請讓我知道什麼是錯在這裏。提前致謝。

+0

作爲一個方面說明:User.from_facebook({UID:existing_user.uid})可以在不花括號寫: User.from_facebook(uid:existing_user.uid) – tessi

+0

有什麼問題?檢查你列出的輸出。您的Facebook用戶對象沒有電子郵件,即無,但您的用戶對象有電子郵件。所以nil == [email protected]是錯誤的。因此,測試失敗 –

回答

1

您的User工廠沒有完全設置用戶。它創建下列user對象:

#<User id: 105, 
     email: "[email protected]", 
     encrypted_password: "$2a$04$90uzEdbwfnq...", 
     reset_password_token: nil, 
     reset_password_sent_at: nil, 
     remember_created_at: nil, 
     sign_in_count: 0, 
     current_sign_in_at: nil, 
     last_sign_in_at: nil, 
     current_sign_in_ip: nil, 
     last_sign_in_ip: nil, 
     created_at: "2015-08-30 04:12:59", 
     updated_at: "2015-08-30 04:12:59", 
     auth_token: "vkvm2-fLe5x1dZGbewqw", 
     provider: nil, 
     uid: "133290925" 

注意,供應商是nil。因此,您的from_facebook方法(查找提供者的uuid )找不到該用戶。

作爲一個解決方案,請使用以下的規範來創建existing_user

existing_user = FactoryGirl.create(:user, provider: 'facebook') 
+0

謝謝@tessi,工作就像一個魅力。 – ruwhan

0

您是否在FactoryGirl.create(:user)中設置uid

你能發佈你的user工廠的內容嗎?您可能想要創建一個設置唯一的facebook_user工廠uid

+0

感謝@Josh,正如@tessi所述,這是因爲我沒有設置'user'的':provider'屬性。 – ruwhan