我对 Rails 应用程序测试还很陌生,我正在尝试向我的应用程序模型之一添加一些基本测试。更具体地说,我使用的是 Shoulda-matchers 3.0.1 和 rspec-rails 3.4.0 gems。我的测试如下:
RSpec.describe User, type: :model do
describe 'validations' do
# Other tests......
describe 'for email' do
it { should validate_uniqueness_of(:email).on(:create) }
end
end
end
在包含以下内容的模型上:
class User < ActiveRecord::Base
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL },
uniqueness: { case_sensitive: false }
# Other stuff for the model....
end
当我运行测试时,它失败并显示以下内容:
1) User validations for email should require case sensitive unique value for email
Failure/Error: should validate_uniqueness_of(:email).on(:create)
Did not expect errors to include "has already been taken" when email is set to "A",
got errors:
* "can't be blank" (attribute: name, value: nil)
* "is invalid" (attribute: email, value: "A")
* "has already been taken" (attribute: email, value: "A")
* "can't be blank" (attribute: password, value: nil)
* "is too short (minimum is 6 characters)" (attribute: password, value: nil)
* "can't be blank" (attribute: password, value: nil)
# ./spec/models/user_spec.rb:41:in `block (4 levels) in <top (required)>'
我非常不知道在这里做什么。 shoulda-matchers 文档非常棒,它确实指出创建初始对象可能会出现问题,他们建议在测试之前显式创建一个对象,这不会改变我的情况,无论哪种方式我都会收到错误。我一定做错了什么,正如我所说,我还没有这种测试的经验。任何方向都将不胜感激。
最佳答案
好的,我快速检查了一下,发现这是因为您在模型中设置了 validates ... uniqueness: { case_sensitive: false }
但您的规范没有相应指定。你可以试试这个:
it { should validate_uniqueness_of(:email).case_insensitive }
此外,我认为这里不需要 on(:create)
。
关于ruby-on-rails - 尝试使用 shoulda-matchers/RSpec 测试唯一性验证时出现 "Did not expect..."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34258106/