【问题标题】:(Rails) Can't use variable made by FactoryBot in rspec(Rails) 不能在 rspec 中使用 FactoryBot 生成的变量
【发布时间】:2022-11-13 23:12:57
【问题描述】:

我有两个模型,帖子和评论 帖子有很多评论

这是我的模式->

  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

所以我尝试在请求方面使用这些。

首先我初始化变量()

-cmets_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 错误?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec ruby-on-rails-5 rspec-rails


    【解决方案1】:

    在评论工厂中使用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) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      相关资源
      最近更新 更多