我有以下規格:RSpec的不比較對象正確
require 'spec_helper'
describe Page do
it "has a valid factory" do
create(:page).should be_valid
end
it "is invalid without a title" do
build(:page, title: nil).should_not be_valid
end
it "finds record" do
page = create(:page, title: 'heyo')
Page.unscoped.where(:title => 'heyo').should == page
end
it "finds record with same attributes" do
page = create(:page, title: 'heyo')
Page.unscoped.where(:title => 'heyo').first.attributes.each do |name, val|
expect(page[name]).to eq(val)
end
end
end
我有以下工廠:
model_statuses = ['published', 'draft']
FactoryGirl.define do
factory :page do
title { Faker::Lorem.word + ' Page' }
slug { title ? title.parameterize : nil }
intro { Faker::Lorem.sentence 10 }
content { Faker::Lorem.sentences(5).join ' ' }
status { model_statuses.sample }
end
end
測試失敗:
Failures:
1) Page finds record with same attributes
Failure/Error: expect(page[name]).to eq(val)
expected: Fri, 24 Jan 2014 23:33:47 MSK +04:00
got: Fri, 24 Jan 2014 23:33:47 MSK +04:00
(compared using ==)
Diff:
# ./spec/models/page_spec.rb:20:in `block (3 levels) in <top (required)>'
# ./spec/models/page_spec.rb:19:in `each'
# ./spec/models/page_spec.rb:19:in `block (2 levels) in <top (required)>'
2) Page finds record
Failure/Error: Page.unscoped.where(:title => 'heyo').should == page
expected: #<Page id: 1, slug: "heyo", title: "heyo", intro: "Sed sint et nesciunt earum libero eveniet est cupid...", content: "A sunt ab exercitationem quas ex incidunt numquam. ...", created_at: "2014-01-24 19:33:47", updated_at: "2014-01-24 19:33:47", status: "draft">
got: [#<Page id: 1, slug: "heyo", title: "heyo", intro: "Sed sint et nesciunt earum libero eveniet est cupid...", content: "A sunt ab exercitationem quas ex incidunt numquam. ...", created_at: "2014-01-24 19:33:47", updated_at: "2014-01-24 19:33:47", status: "draft">] (using ==)
爲什麼這些對象他們的屬性是不一樣的,我如何正確檢查對象的平等?
謝謝。存根'Time.now'的最佳方法是什麼?在RSpec中通常如何比較對象?什麼是最佳實踐? – leemour
我將如何在代碼中提出/檢查以查看實際值? – leemour
@leemour當我說舉起/檢查時,我的意思是在失敗的測試中調用'raise page.inspect',例如在您的「查找記錄」示例中。 – TreyE