我有点困惑:
class SessionsController < ApplicationController
def new
@user = User.new
end
end
我原以为所有以下三个期望都会过去:
require 'spec_helper'
describe SessionsController do
describe '#new' do
let(:user) { FactoryGirl.build(:user, name: nil, email: nil, password: nil, password_confirmation: nil)}
before { get :new }
it { expect(assigns(:user)).to eq user }
it { expect(assigns(:user)).to eq User.new }
it "should assign stubbed user" do
assigns(:user).should eq user
end
end
end
然而我明白了: FFF
故障:
1) SessionsController#new should eq #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
Failure/Error: it { expect(assigns(:user)).to eq user }
expected: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
got: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
(compared using ==)
Diff:
# ./spec/controllers/sessions_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
2) SessionsController#new should eq #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
Failure/Error: it { expect(assigns(:user)).to eq User.new }
expected: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
got: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
(compared using ==)
Diff:
# ./spec/controllers/sessions_controller_spec.rb:10:in `block (3 levels) in <top (required)>'
3) SessionsController#new should assign stubbed user
Failure/Error: assigns(:user).should eq user
expected: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
got: #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil>
(compared using ==)
Diff:
# ./spec/controllers/sessions_controller_spec.rb:13:in `block (3 levels) in <top (required)>'
我的意思是什么? Diff
部分甚至是空的。如果我使用be
匹配器,我会理解,但我正在使用eq
,那么发生了什么?
答案 0 :(得分:1)
在ActiveRecord中,如果两个模型对象具有相同的类和相同的非零主键值,则认为它们是相等的。
因此,如果两个相同的对象具有零id
个值,则它们不相等。
请参阅https://github.com/rails/rails/blob/master/activerecord/lib/active_record/core.rb#L290
这可能看起来很奇怪,但如果您认为那两个对象(如果它们曾经保存过)将由数据库分配两个不同的id
值,那么这是有意义的。因此,在分配ActiveRecord模型对象的id
之前,无法将其与另一个进行有意义的比较。
答案 1 :(得分:0)
尝试使用eq方法比较user.attributes
,它应该通过。