在測驗我的模型時,我使用的是 FactoryBot 生成的資料。在模型內部,我提到了out_of_print的驗證為True。在運行測驗用例時,它說不能接受 nil 值。
'書籍型號代碼'
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
uj5u.com熱心網友回復:
使用 on 布爾欄位驗證存在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]
檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433910.html
標籤:轨道上的红宝石 单元测试 rspec 工厂机器人 骗子
