【问题标题】:Create reusable class for test data in rspec在 rspec 中为测试数据创建可重用类
【发布时间】:2021-07-22 11:29:23
【问题描述】:

我想创建一个方法来快速创建测试数据进行测试。 所以我创建了 FakeItemGroupCreation 类,但是我得到了这个错误

FakeItemGroupCreation:Class 的未定义方法“create”

如何使用 create 方法?这是解决此问题的最佳做法吗?

require 'rails_helper'
RSpec.describe ItemGroupCreator, type: :model do
 

  before(:each) do
    @profile = create(:profile)
    @category = create(:category)
  end
  
  class FakeItemGroupCreation
    def self.create_same_category(profile, category, item_ids_pairs)
      item_ids_pairs.each do |item_ids|
        item_ids.each do |id| 
          create(:item, id: id, profile_id: profile.id, category: category)
        end
        # Creating other nested records..and perform calculations
      end
    end
  end 

  it 'test with existing data A' do
    existing_matrix = [ [4,5,6], [1,2,3] ]
    FakeItemGroupCreation.create_same_category(@profile,  @category, existing_matrix)
  end 

  it 'test with existing data B' do
    existing_matrix = [ [7,8,8], [4,5,2] ]
    FakeItemGroupCreation.create_same_category(@profile,  @category, existing_matrix)
  end 

  

【问题讨论】:

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


    【解决方案1】:

    您打算包装的是 FactoryBot 的 create 吗?如果是这样,请明确使用它

    FactoryBot.create(:item, ...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      相关资源
      最近更新 更多