我有 2 個模型:Answer 和 Book。
盡管它們非常相似,但所有測驗都通過了 Answer 但 1 個測驗失敗了 Book
模型/答案.rb
class Answer < ApplicationRecord
belongs_to :question, class_name: "Question", foreign_key: "question_id"
validates :text, presence: true
validates :correct, presence: true
validates :question_id, presence: true
end
模型/book.rb
class Book < ApplicationRecord
belongs_to :grade, class_name: "Grade", foreign_key: "grade_id"
validates :name, presence: true, uniqueness: { case_sensitive: false }
validates :grade_id, presence: true
end
規格/工廠/answers.rb
FactoryBot.define do
factory :answer do
text { Faker::Book.author }
correct { %i(false, true).sample }
question
end
end
規格/工廠/books.rb
FactoryBot.define do
factory :book do
name { Faker::Book.title }
grade
end
end
光譜/模型/answer_spec.rb
require 'rails_helper'
RSpec.describe Answer, type: :model do
describe 'validation' do
it { should validate_presence_of(:text) }
it { should validate_presence_of(:correct) }
it { should validate_presence_of(:question_id) }
it { should belong_to :question }
end
end
光譜/模型/book_spec.rb
require 'rails_helper'
RSpec.describe Book, type: :model do
describe 'validation' do
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:name).case_insensitive }
it { should validate_presence_of(:grade_id) }
it { should belong_to :grade }
end
end
我得到的回報是:
圖書驗證應驗證 :name 是不區分大小寫的唯一失敗/錯誤:它 { should validate_uniqueness_of(:name).case_insensitive }
Shoulda::Matchers::ActiveRecord::ValidateUniquenessOfMatcher::ExistingRecordInvalid: validate_uniqueness_of 的作業原理是將新記錄與現有記錄進行匹配。如果沒有現有記錄,它將使用您提供的記錄創建一個。
While doing this, the following error was raised: **PG::NotNullViolation: ERROR: null value in column "grade_id" violates not-null constraint** DETAIL: Failing row contains (2, null, null, 2021-12-23 15:03:39.977355, 2021-12-23 15:03:39.977355). The best way to fix this is to provide the matcher with a record where any required attributes are filled in with valid values beforehand.
I have tried many ways that I came up with or saw in stack/git posts but none seams to work.
uj5u.com熱心網友回復:
這種情況在validates_uniqueness_of 檔案中有介紹。
如果沒有現有記錄,它將使用您提供的記錄創建一個。
你的規范沒有說明如何創建一本書,也不知道它需要一個等級。你需要告訴它,它不會使用工廠。通過添加一個主題供您的單線使用來做到這一點。
require 'rails_helper'
RSpec.describe Book, type: :model do
subject { build(:book) }
describe 'validation' do
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:name).case_insensitive }
it { should belong_to :grade }
end
end
請注意,it { should validate_presence_of(:grade_id) }與it { should belong_to :grade }. own_to 已經驗證存在。
uj5u.com熱心網友回復:
在具有參考的模型中嘗試測驗唯一性時,您需要先提供一個進行比較。
為此,您應該指定主題:
describe 'validation' do
subject{
}
之后,您可以呼叫 FactoryBot 來構建要與之競爭的:
FactoryBot.build(:book)
最后一段:
describe 'validation' do
subject{
FactoryBot.build(:book)
}
[Schwern][1] 先生將代碼增強了一點:
describe 'validation' do
subject{ build(:book)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/398976.html
標籤:ruby-on-rails testing rspec-rails shoulda-matchers
