【问题标题】:Getting a "Did not expect..." error when trying to test uniqueness validation using shoulda-matchers/RSpec尝试使用 shoulda-matchers/RSpec 测试唯一性验证时出现“没想到...”错误
【发布时间】:2015-12-14 00:27:54
【问题描述】:

我对在 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 文档很棒,它确实指出创建初始对象可能会出现问题,他们建议在测试之前明确创建一个对象,这在我的情况下不会改变任何东西,无论哪种方式我都会遇到错误。我一定是做错了什么,正如我所说我还没有经历过这种测试。非常感谢任何方向。

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    好的,我快速检查了一下,发现这是因为您在模型中设置了validates ... uniqueness: { case_sensitive: false },但您的规范没有相应指定。你可以试试这个:

    it { should validate_uniqueness_of(:email).case_insensitive }
    

    另外,我认为这里不需要on(:create)

    【讨论】:

    • 就这样,我欠另一个来自 Stack Overflow 的人一个冷漠。谢谢你,我的朋友,就是这样。
    猜你喜欢
    • 2014-04-05
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多