Search code examples
ruby-on-railsrspecrspec-rails

Create reusable class for test data in rspec


I want to create a method to quickly create test data for test. So I've created the FakeItemGroupCreation class, but I got this error

undefined method `create' for FakeItemGroupCreation:Class

How can I use the create method? Is this the best practice to solve this problem?

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 

  

Solution

  • Is it FactoryBot's create you intend to be wrapping? If so, use it explicitly

    FactoryBot.create(:item, ...)