2014-01-13 76 views
0

我在測試用戶之間的聊天內容。我使用的RSpec和FactoryGirl爲什麼rails中的「where」查詢返回不同的對象?

,這不是通過測試:

it "creates a chat if one does not exist" do 
    bob = create(:user, username: "bob") 
    dan = create(:user, username: "dan") 
    new_chat = Chat.create(user_id: @dan.id, chatted_user_id: bob.id) 
    expect(Chat.where("chatted_user_id = ?", bob.id).first).to equal(new_chat) 
end 

失敗消息稱:

Failure/Error: expect(Chat.where("chatted_user_id = ?", bob.id).first).to equal(new_chat) 

    expected #<Chat:70120833243920> => #<Chat id: 2, user_id: 2, chatted_user_id: 3> 
     got #<Chat:70120833276240> => #<Chat id: 2, user_id: 2, chatted_user_id: 3> 

    Compared using equal?, which compares object identity, 
    but expected and actual are not the same object. Use 
    `expect(actual).to eq(expected)` if you don't care about 
    object identity in this example. 

爲什麼我的查詢返回不同的對象ID?

回答

2

equal檢查對象的身份。您正在測試的對象是引用同一記錄的兩個對象(實例),但實際上它們是從Ruby虛擬機角度看的不同對象。

您應該使用

expect(Chat.where("chatted_user_id = ?", bob.id).first).to eq(new_chat) 

爲了更好地理解這個問題,看看下面的例子

2.0.0-p353 :001 > "foo".object_id 
=> 70117320944040 
2.0.0-p353 :002 > "foo".object_id 
=> 70117320962820 

在這裏,我創建了兩個相同的字符串。它們是相同的,但並不相同,因爲它們實際上是兩個不同的對象。

2.0.0-p353 :008 > "foo" == "foo" 
=> true 
2.0.0-p353 :009 > "foo".equal? "foo" 
=> false 

這是影響您的測試的相同問題。 equal檢查兩個對象在object_id級別是否實際相同。但是你真正想知道的是他們是否是同一個記錄。

+0

謝謝西蒙娜!那麼==和eq一樣嗎?他們是否只是檢查對象的「價值」?另外,你能否提出有關ActiveRecord實例的更多信息? –

+0

是的,'eq'是'=='的RSpec匹配器。 –

相關問題