我还是在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-matcher的文档很棒,它确实说明创建一个初始对象可能存在问题,并建议在测试之前明确创建一个,在我的情况下没有改变任何东西,我得到错误办法。我必须做错事,因为我说我还没有经历过这种测试。任何方向都非常感谢。
答案 0 :(得分:3)
好的,我进行了快速检查并看到了它,因为您在模型中设置了validates ... uniqueness: { case_sensitive: false }
,但您的规格没有相应指定。你可以试试这个:
it { should validate_uniqueness_of(:email).case_insensitive }
另外,我认为这里不需要on(:create)
。