2016-08-23 102 views
0

當我測試我的控制器,我做了一件這樣的失敗:RSpec的比較空的ActiveRecord ::關係

bar = SuperDuper.calculate(resource) 
expect(assigns(:foo)).to eq(bar) 

我得到這個結果

expected: #<ActiveRecord::Relation []> 
    got: #<ActiveRecord::Relation []> 

(compared using ==) 

爲什麼RSpec的認爲這是失敗?

正如你所看到的,我使用eq忽略了對象標識,而不是equal,它比較了對象標識。

+0

也許rspec通過鏈接斷言對象是相等的。所以你有兩個相同的對象,但它們指向內存中的不同區域。考慮比較價值而不僅僅是對象比較 – tmn4jq

+0

@ tmn4jq在這裏我使用'eq'來比較值,而不是使用'equal'來比較對象標識 –

+0

調試與'expect(assigns(:foo).to_a).to eq bar.to_a)'或'expect(賦值(:foo).to_sql).to eq(bar.to_sql)'。 –

回答

0

我不確定,但你eq意味着==。證明:https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/equality-matchers

還應注意這個: a.eql?(b) # object equivalence - a and b have the same value

從這兒:Rspec `eq` vs `eql` in `expect` tests

所以,我認爲你應該嘗試eql匹配。

+0

我得到這個: '預計:#''得到:#''(使用eql進行比較)' –

+1

@MohamedAnwer考慮閱讀:http: //stackoverflow.com/questions/26482564/rspec-eq-matcher-returns-failure-when-two-things-are-equal,https://www.relishapp.com/rspec/rspec-rails/docs/matchers/ activerecord-relation-match-array和http://stackoverflow.com/questions/26935630/rspec-matchers-when-working-with-activerecordrelation – tmn4jq