ruby-on-rails 为什么我在工厂中得到这个错误:一定是已有的卡,怎么解?

y4ekin9u  于 2023-02-26  发布在  Ruby
关注(0)|答案(2)|浏览(125)

bounty已结束。回答此问题可获得+50声望奖励。奖励宽限期将在5小时后结束。react1希望引起更多人关注此问题。

只有我想创建一个'职位',但我得到这个错误:

Failure/Error: let!(:post) { FactoryBot.create(:post, company_id: company.id, card_id: card.id) } 
ActiveRecord::RecordInvalid:
        Validation failed: must be exist card

这就是我创建对象post的方法

RSpec.describe 'Sections', type: :request do
let!(:company) { FactoryBot.create :company }
let!(:card) { FactoryBot.create(:card, company_id: company.id) }
let!(:post) { FactoryBot.create(:post, company_id: company.id, card_id: card.id) }

岗位的模式是:

class Post < ApplicationRecord
  validates :first_title, :sub_title, :email, presence: true
  belongs_to :card
  delegate :max, to: :card
end

和卡片:

class Card < ApplicationRecord
  include Discard::Model
end

工厂:

factory :post do
    first_title { Faker::Name.name }
    sub_title { Faker::Name.name }
    email { Faker::Internet.email}
    card_id {}
  end

卡片工厂:

factory :card do
  company_id {}
end
ilmyapht

ilmyapht1#

看起来你的工厂没有很好的定义。这应该是确保它正常工作的第一件事。试着像这样定义"关联":

factory :post do
  first_title { Faker::Name.name }
  sub_title { Faker::Name.name }
  email { Faker::Internet.email }
  card
end

或者:

factory :post do
  first_title { Faker::Name.name }
  sub_title { Faker::Name.name }
  email { Faker::Internet.email }
  card { FactoryBot.create(:card) }
end

或者,您也可以尝试使用association宏:

factory :post do
  first_title { Faker::Name.name }
  sub_title { Faker::Name.name }
  email { Faker::Internet.email}
  association :card, factory: :card
end
sg3maiej

sg3maiej2#

编译另一个问题的回答:

factory :card do
  association :company, factory: :company
end

factory :post do
  first_title { Faker::Name.name }
  sub_title { Faker::Name.name }
  email { Faker::Internet.email}

  transient do
    company_id { FactoryBot.create(:company).id }
  end

  after(:build) do |post, evaluator|
    card = FactoryBot.create(:card, company_id: evaluator.company_id)
    post.card = card
  end
end

let(:company) { FactoryBot.create :company }
let!(:post) { FactoryBot.create(:post, company_id: company.id }
let(:card) { post.card }

相关问题