Rspec 使用 FactoryBot 进行测试 - ActiveRecord::InvalidRecord 错误

Rspec testing with FactoryBot - ActiveRecord::InvalidRecord Error

在测试我的模型时,我使用的是 FactoryBot 生成的数据。在模型内部,我提到 out_of_print 的验证为 True。虽然运行它说的测试用例不能接受零值。

'Book model code'

class Book < ApplicationRecord
  belongs_to :supplier
  belongs_to :author
  has_many :reviews

  validates :price, :year_published,:views, presence: true
  validates :title, presence: true, uniqueness: true
  validates :out_of_print,presence: true

  scope :in_print, -> { where(out_of_print: false) }
  scope :out_of_print, -> { where(out_of_print: true) }
  scope :old, -> { where('year_published < ?', 50.years.ago )}
  scope :out_of_print_and_expensive, -> { out_of_print.where('price > 500') }
  scope :costs_more_than, ->(amount) { where('price > ?', amount) }
end 

“书籍工厂”

FactoryBot.define do
  factory :book do
    title { Faker::Name.name}
    year_published { Faker::Number.within(range: 1800..2020) }
    price { "9.99" }
    out_of_print {false}
    views { Faker::Number.between(from: 100, to: 1000) }
    association :author
    association :supplier
  end
end

“测试代码”

  describe 'create' do
    it "should create a valid book" do
     author = create(:author)
     # author.save
     supplier = create(:supplier)
     # supplier.save
     # book = build(:book,supplier: supplier,author: author)
     book = create(:book,supplier: supplier,author: author)

     # book.save
     # puts(book.errors.full_messages)
     expect(book.save).to eq(true)
    end
   end
 end

“错误”

失败:

 1) Book create should create a valid book
 Failure/Error: book = create(:book,supplier: supplier,author: author)
 
 ActiveRecord::RecordInvalid:
   Validation failed: Out of print can't be blank

在布尔字段上使用 presence: true 验证存在将始终要求值为 true

presence 验证使用 blank? 检查值是 nil 还是空字符串。

但是对于布尔值:

true.blank? => false
false.blank? => true

验证布尔字段应如下所示:

validates :out_of_print, inclusion: [true, false]
# or
validates :out_of_print, exclusion: [nil]

Docs.