我在user_spec.rb
中的以下代码中工作得很好
#spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, :type => :model do
it 'is invalid with an alternate phone number that is also that user\'s primary phone' do
expect(FactoryGirl.build(:user, primary_phone: '123-456-7890', alternate_phone: '123-456-7890').save).to be_falsey
end
end
直到我更改了以下代码
#app/models/user.rb
def primary_phone=(num)
write_attribute(:primary_phone, self.number_to_phone(num))
end
到
#app/models/user.rb
def primary_phone=(num)
write_attribute(:primary_phone, self.number_to_phone(num, country_code: 1))
end
现在测试失败并出现以下错误
Failures:
1) User is invalid with an alternate phone number that is also that user's primary phone
Failure/Error: expect(FactoryGirl.build(:user, primary_phone: '123-456-7890', alternate_phone: '123-456-7890').save).to be_falsey
expected: falsey value
got: true
# ./spec/models/user_spec.rb:80:in `block (2 levels) in <top (required)>'
# ./spec/rails_helper.rb:62:in `block (3 levels) in <top (required)>'
# /home/pavan/.rvm/gems/ruby-2.2.1/gems/database_cleaner-1.3.0/lib/database_cleaner/generic/base.rb:15:in `cleaning'
# /home/pavan/.rvm/gems/ruby-2.2.1/gems/database_cleaner-1.3.0/lib/database_cleaner/base.rb:92:in `cleaning'
# /home/pavan/.rvm/gems/ruby-2.2.1/gems/database_cleaner-1.3.0/lib/database_cleaner/configuration.rb:86:in `block (2 levels) in cleaning'
# /home/pavan/.rvm/gems/ruby-2.2.1/gems/database_cleaner-1.3.0/lib/database_cleaner/configuration.rb:87:in `call'
# /home/pavan/.rvm/gems/ruby-2.2.1/gems/database_cleaner-1.3.0/lib/database_cleaner/configuration.rb:87:in `cleaning'
# ./spec/rails_helper.rb:61:in `block (2 levels) in <top (required)>'
Finished in 19.04 seconds (files took 17.2 seconds to load)
118 examples, 1 failure, 70 pending
我认为更改的电话号码格式导致问题并且已更改
it 'is invalid with an alternate phone number that is also that user\'s primary phone' do
expect(FactoryGirl.build(:user, primary_phone: '123-456-7890', alternate_phone: '123-456-7890').save).to be_falsey
end
到
it 'is invalid with an alternate phone number that is also that user\'s primary phone' do
expect(FactoryGirl.build(:user, primary_phone: '+1-123-456-7890', alternate_phone: '+1-123-456-7890').save).to be_falsey
end
但错误存在。我不知道发生了什么。非常感谢任何帮助。
答案 0 :(得分:1)
您的测试现在返回true,因为用户的电话号码为+1-123-456-7890
,您的备用号码将为123-456-7890
。这是因为您在+1-
之前添加了额外的primary_phone
,而不是alternate_phone
。
您应该添加此
def alternate_phone=(num)
write_attribute(:alternate_phone, self.number_to_phone(num, country_code: 1))
end
或者将测试更改为
it 'is invalid with an alternate phone number that is also that user\'s primary phone' do
expect(FactoryGirl.build(:user, primary_phone: '123-456-7890', alternate_phone: '+1-123-456-7890').save).to be_falsey
end