ruby-on-rails - 为什么我的模型的唯一性验证规范在应该通过时却失败了?

标签 ruby-on-rails ruby ruby-on-rails-4 rspec rspec-rails

我正在学习使用 RSpec 进行测试。我的测试有问题。

我的模型:

class User < ActiveRecord::Base
  has_secure_password

  # Validation macros
  validates_presence_of :name, :email
  validates_uniqueness_of :email, case_sensitive: false
end

我的工厂:

FactoryGirl.define do
  factory :user do
    name "Joe Doe"
    email "joe@example.com"
    password_digest "super_secret_password"
  end
end

还有我的规范:

require 'rails_helper'

RSpec.describe User, type: :model do
  user = FactoryGirl.build(:user)

  it 'has a valid factory' do
    expect(FactoryGirl.build(:user)).to be_valid
  end

  it { is_expected.to respond_to(:name) }
  it { is_expected.to respond_to(:email) }
  it { is_expected.to respond_to(:password) }
  it { is_expected.to respond_to(:password_confirmation) }

  it { expect(user).to validate_presence_of(:name) }
  it { expect(user).to validate_presence_of(:email) }
  it { expect(user).to validate_presence_of(:password) }
  it { expect(user).to validate_uniqueness_of(:email).case_insensitive }
end

我希望这次测试能通过。但我得到的结果是:

Failures:

1) User should validate that :email is case-insensitively unique Failure/Error: it { expect(user).to validate_uniqueness_of(:email).case_insensitive }

   User did not properly validate that :email is case-insensitively unique.
     The record you provided could not be created, as it failed with the
     following validation errors:

     * name: ["can't be blank"]
 # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'

Finished in 0.34066 seconds (files took 1.56 seconds to load) 9 examples, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:18 # User should validate that :email is case-insensitively unique

我错过了什么?

更新

我认为这是一个错误:https://github.com/thoughtbot/shoulda-matchers/issues/830

最佳答案

这是因为您在 IMO 中声明了 2 次!首先构建用户,然后在 expect() 中构建相同的用户。

只需像这样使用您使用 factory-bot 构建的第一个用户:

it 'has a valid factory' do
    expect(user).to be_valid
end

附言 最好使用 Faker gem 而不是像在 factory.rb

中那样使用硬编码实例

关于ruby-on-rails - 为什么我的模型的唯一性验证规范在应该通过时却失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34830015/

相关文章:

ruby-on-rails - 在 SASS 文件和 Rails erb 模板之间共享颜色

ruby-on-rails - 使用 Ruby Win32ole 发送格式化/html Outlook 电子邮件

ruby-on-rails - button_to 使用 GET 方法

ruby-on-rails - Minimagick:未定义方法 `destroy!' 为 true:TrueClass auto_orient

Ruby - 在 Iterator each 中工作 "yield"

ruby-on-rails - Rails pg gem不兼容的库版本

ruby-on-rails - RSpec 中调用的模型方法不会更改测试数据库中的对象

ruby-on-rails - RubyOnRails 设计的单点登录策略

ruby lambda 上下文

ruby-on-rails - 通过代理运行 Web 请求时如何设置 use_ssl 参数?