ruby-on-rails - Rspec 忽略唯一性验证

标签 ruby-on-rails ruby rspec validates-uniqueness-of

我不希望 rspec 让我用相同的名称保存该类的两个对象,但它确实如此。我有什么遗漏的吗?

我的模型:

class Product < ActiveRecord::Base
  validates :title, :description, :image_url, presence: true
  validates :price, numericality: {greater_than_or_equal_to: 0.01}
  validates :title, uniqueness: true
  validates :image_url, allow_blank: true, format: {
    with: %r{\.(gif|jpg|png)\Z}i,
    message: 'must be a URL for GIF, JPG or PNG image'
  }
end

我的测试:

describe "when creating products with identical names" do
    let(:book1) { FactoryGirl.create(:product, title: 'identical') }
    let(:book2) { FactoryGirl.build(:product, title: 'identical') }

    it "raises unique validation error" do
        expect(book2).not_to be_valid
    end
end

这就是我得到的:

1) Product when creating products with identical names raises unique validation error
     Failure/Error: expect(book2).not_to be_valid
       expected #<Product id: nil, title: "identical", description: "Some crazy wibbles, that are fun", image_url: "freddie_mercury.jpg", price: #<BigDecimal:7f995cdd1358,'0.5699E2',18(27)>, created_at: nil, updated_at: nil> not to be valid

我什至可以写两次FactoryGirl.create,它就可以保存。

但是,如果我切换到 Rails 控制台并尝试创建两个具有两个相同名称的对象,则会收到错误。我的测试环境有问题吗?

最佳答案

嗯,book1 未在您的测试运行中创建...考虑更改:

describe "when creating products with identical names" do
  let(:book1) { FactoryGirl.create(:product, title: 'identical') }
  let(:book2) { FactoryGirl.build(:product, title: 'identical') }

  it "raises unique validation error" do
    expect(book2).not_to be_valid
  end
end

describe "when creating products with identical names" do
  let(:book) { FactoryGirl.build(:product, title: 'identical') }

  before do
    FactoryGirl.create(:product, title: 'identical')
  end

  it "raises unique validation error" do
    expect(book).not_to be_valid
  end
end

这应该有帮助!祝你好运!

关于ruby-on-rails - Rspec 忽略唯一性验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29345146/

相关文章:

ruby-on-rails - 模型属性代理

Ruby 固定数字大十进制舍入

ruby-on-rails - 如果失败, `update_attribute` 会返回什么?

Mysql2::错误:表不存在:显示来自 `sessions` 的完整字段

ruby-on-rails - 使用 Minitest 跳过 Pundit 授权

mysql - Rails 3 - 尝试创建/迁移空白数据库名称的 Beta 环境

ruby-on-rails - 由多个 Controller 和模型共享的代码——保存它的最佳位置在哪里?

ruby-on-rails-3 - 我如何将每个 rspec 的描述打印到 Rails.logger?

rspec - 如何避免工厂女孩对象的持久性

ruby-on-rails - 如何使用 RSpec 和 Capybara 测试 JQuery 文件上传