我在我的rails应用程序中使用设计用于授权目的,并且在开发的单元测试部分中遇到了一些问题。
it "is invalid with a duplicate email address" do
User.create(
name: 'Joe', surname: 'Tester', email: 'tester@example.com', password: 'password123', password_confirmation: 'password123'
)
user = User.new(
name: 'Jane', surname: 'Tester', email: 'tester@example.com', password: 'password123', password_confirmation: 'password123'
)
pp user.errors.inspect
expect(user).to have(1).errors_on(:email)
end
但为此,我得到expected 1 errors on :email, got 2
您能否建议我如何弄清楚其他错误是什么?我试过pp user.errors.inspect
,但那不是很有用。
谢谢。
修改
pp user.errors.inspect
得出以下结论:
"#<ActiveModel::Errors:0x000000058016c8 @base=#<User id: nil, name: \"Jane\", surname: \"Tester\", about: nil, level: nil, city: nil, created_at: nil, updated_at: nil, email: \"tester@example.com\", encrypted_password: \"$2a$04$TfDBOXXDhUDVuJhPmxbu9eRZsTQ.Om8X5k5YkeDg51e...\", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>, @messages={}>"
F
Failures:
1) User is invalid with a duplicate email address
Failure/Error: expect(user).to have(1).errors_on(:email)
expected 1 errors on :email, got 2
答案 0 :(得分:0)
这个测试似乎很难维护(如果你将另一个属性设置为强制,你必须重构这个测试)。
您可能希望定义测试以实际尊重其描述:
it "is invalid without a password" do
User.create(name: 'Joe', surname: 'Tester', email: 'tester@example.com', password: 'password123', password_confirmation: 'password123')
user = User.create(email: 'tester@example.com')
user.should_not be_valid
user.errors.messages[:email].present?.should be true
end