我在RSpec测试中比较两个地址对象,但即使属性看起来具有相同的值,测试也会失败。我正在使用expect(object1).to eq(object2)
并收到以下输出:
Failures:
1) Property#address= sets all address fields
Failure/Error: expect(property).to eq(property_address)
expected: #<Property id: nil, property_type_id: nil, street: "780 Monterey Blvd", unit: "301", city: "San Francisco", state: "CA", zip: "94127", country: "US", square_feet: "906", beds: "2", baths: "1", floors: "1", created_at: nil, updated_at: nil, user_id: 348>
got: #<Property id: nil, property_type_id: nil, street: "780 Monterey Blvd", unit: "301", city: "San Francisco", state: "CA", zip: "94127", country: "US", square_feet: "906", beds: "2", baths: "1", floors: "1", created_at: nil, updated_at: nil, user_id: 348>
(compared using ==)
Diff:
使用pry-rescue
查看实际属性并进行比较,我会收到以下信息:
[3] pry(RSpec::Expectations)> actual.attributes
=> {"id"=>nil,
"property_type_id"=>nil,
"street"=>"780 Monterey Blvd",
"unit"=>"301",
"city"=>"San Francisco",
"state"=>"CA",
"zip"=>"94127",
"country"=>"US",
"square_feet"=>"906",
"beds"=>"2",
"baths"=>"1",
"floors"=>"1",
"created_at"=>nil,
"updated_at"=>nil,
"user_id"=>335}
[4] pry(RSpec::Expectations)> expected.attributes
=> {"id"=>nil,
"property_type_id"=>nil,
"street"=>"780 Monterey Blvd",
"unit"=>"301",
"city"=>"San Francisco",
"state"=>"CA",
"zip"=>"94127",
"country"=>"US",
"square_feet"=>"906",
"beds"=>"2",
"baths"=>"1",
"floors"=>"1",
"created_at"=>nil,
"updated_at"=>nil,
"user_id"=>335}
[5] pry(RSpec::Expectations)> differ.diff(actual.attributes, expected.attributes)
=> "\e[0m\n\e[0m"
我无法发现任何差异。 diff
- 差异来自哪里?
解
我在How to test for (ActiveRecord) object equality中没有听到答案的原因是,在pry-rescue
中,输出结果为
differ.diff(actual.attributes, expected.attributes)
显示与实际失败规范相同的差异。但是,按照How to test for (ActiveRecord) object equality的答案,我试了一下并更改了实际规格以使用expect(property.attributes).to eq(property_address.attributes)
,现在规范通过了。