简体   繁体   English

(Rails) 不能使用 FactoryBot 在 rspec 中创建的变量

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

i have two model, post and comment post has many comment我有两个model,发帖和评论帖子有很多评论

this is my schema ->这是我的模式->

  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

and my route is like ->我的路线就像->

  resources :posts do
    resources :comments
  end

my post factory ->我的邮局 ->

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

my comment factory ->我的评论工厂 ->

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

so i tried to use these in request respec.所以我尝试在请求规范中使用这些。

first i init the variable ()首先我初始化变量()

-comments_spec.rb -comments_spec.rb

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

then i use it然后我用它

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

but i get this error ->但我得到这个错误 - >

     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".

how can i change it to check access edit page?我如何更改它以检查访问编辑页面? and why my result makes InvalidForeignKey error?为什么我的结果会导致 InvalidForeignKey 错误?

use association in comment factory to create a post and associate to comment在评论工厂中使用association创建帖子并关联评论

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

Then you can pass created post as a param while creating new comment.然后您可以在创建新评论时将创建的帖子作为参数传递。 If you do not pass the post as a param then it will create a new post using the factory defined for the post and associate it to a comment.如果您不将帖子作为参数传递,那么它将使用为帖子定义的工厂创建一个新帖子并将其关联到评论。

 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

U can use association in factory.你可以在工厂中使用关联。 Bonus: U can also use association model id in factory.奖励:您还可以在工厂中使用协会 model id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM