你好,我正在使用rspec来测试我的用户模型。我只是想知道我所做的是不是测试中的一种常见做法。为了测试错误消息,我做了如下操作
User.create!(users(:first))
user.update_attributes email: 'IDon\'tThinkThisIsAValidEmail'
user.should_not be_valid
assert user.errors.messages.include? :email另外,我该如何测试重复项呢?调用full_messages并测试“电子邮件已被占用”消息?这是一个很好的实践吗?我之所以这样做测试,是因为在我的should_not之前,be_valid测试是通过的,因为用户名无效,所以这是不好的。我所做的是一个好主意吗?有没有更好的测试方法?
发布于 2013-02-03 04:22:19
为了验证电子邮件的格式,您可以执行类似以下操作。请注意,您不必创建用户记录或使用fixture来编写大多数验证规范。
it "will not allow invalid email addresses" do
user = User.new(email: 'notAValidEmail')
user.should have(1).error_on(:email)
end
it "will allow valid email addresses" do
user = User.new(email: 'valid@email.com')
user.should have(:no).errors_on(:email)
end要验证在线状态,您可以执行以下操作:
it { should validate_presence_of(:email) }有关更多示例,请参阅rspec文档:
https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/model-specs/errors-on
发布于 2013-02-03 04:16:28
您应该查看shoulda gem,它有一套有用的测试断言,包括唯一性验证:
describe User do
should validate_uniqueness_of(:email)
end编辑:Here's a link to the docs as a great place to start。
https://stackoverflow.com/questions/14665991
复制相似问题