ruby-on-rails - 尝试使用 shoulda-matchers/RSpec 测试唯一性验证时出现 "Did not expect..."错误

标签 ruby-on-rails ruby rspec

我对 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/

相关文章:

ruby-on-rails - 安装 rails 错误 : could not find rails locally or in a repository

ruby - `alias_method` 私有(private)方法

ruby-on-rails - cucumber 和 rails : testing for the presence of a random record

ruby - 无法使用 rspec 和 Grape 设置自定义 header 参数

ruby-on-rails - 尝试销毁实例时参数数量错误(1 代表 0)

ruby-on-rails - 如何专门使用 "Elasticsearch"gem 将 elasticsearch 与 rails 应用程序集成

sql - 带有哈希值的 Activerecord Where

ruby-on-rails - 如何使用javascript更改image_tag源

ruby - 在模块/类之间共享全局记录器

ruby-on-rails - 使用 RSpec 测试模型中记录的正确顺序