簡體   English   中英

(Rails) 不能使用 FactoryBot 在 rspec 中創建的變量

[英](Rails) Can't use variable made by FactoryBot in rspec

我有兩個model,發帖和評論帖子有很多評論

這是我的模式->

  create_table 'posts', force: :cascade do |t|
    t.string 'title'
  end

  create_table 'comments', force: :cascade do |t|
    t.references :post, index: true, foreign_key: { on_delete: :cascade }
    t.string 'content'
  end

我的路線就像->

  resources :posts do
    resources :comments
  end

我的郵局 ->

FactoryBot.define do
  factory :post do
    sequence(:title) { |n| "title #{n}" }
  end
end

我的評論工廠 ->

FactoryBot.define do
  factory :comment do
    sequence(:content) { |n| "content #{n}" }
    sequence(:post_id) { |n| n }
  end
end

所以我嘗試在請求規范中使用這些。

首先我初始化變量()

-comments_spec.rb

  let(:new_post) { create(:post) }
  let(:comment) { create(:comment) }

然后我用它

  describe '#edit' do
    it 'returns :edit view' do
      get edit_post_comment_path(new_post, comment)
      expect(response).to be_successful
    end
  end

但我得到這個錯誤 - >

     Failure/Error: let(:comment) { create(:comment) }
     
     ActiveRecord::InvalidForeignKey:
       PG::ForeignKeyViolation: ERROR:  insert or update on table "comments" violates foreign key constraint "fk_rails_2fd19c0db7"
       DETAIL:  Key (post_id)=(3) is not present in table "posts".

我如何更改它以檢查訪問編輯頁面? 為什么我的結果會導致 InvalidForeignKey 錯誤?

在評論工廠中使用association創建帖子並關聯評論

FactoryBot.define do
  factory :comment do
    sequence(:content) { |n| "content #{n}" }
    association :post
  end
end

然后您可以在創建新評論時將創建的帖子作為參數傳遞。 如果您不將帖子作為參數傳遞,那么它將使用為帖子定義的工廠創建一個新帖子並將其關聯到評論。

 let(:new_post) { create(:post) }
 let(:comment) { create(:comment, post: new_post) }
FactoryBot.define do
  factory :comment do
   sequence(:content) { |n| "content #{n}" }
   post_id { 1 }     #or post_id { Post&.first&.id }   
  end
end

你可以在工廠中使用關聯。 獎勵:您還可以在工廠中使用協會 model id。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM