繁体   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