Search code examples
ruby-on-railsunit-testingrspecfactory-botshoulda-matchers

For an ActiveRecord model with overridden `New` method, how to provide custom test subject with parameters using FactoryGirl in Rails shoulda matchers


I have an Rails ActiveRecord model which has the new method overridden. The new method accepts a parameter and instantiates an object of this model, with other required fields.

In RSpec Model specs with Shoulda matchers, I'm testing associations.

How can I pass a custom test subject using FactoryGirl?

The Model is:

class Document < ApplicationRecord
  has_many :folders, dependent: :destroy
  belongs_to :project
  belongs_to :author, class_name: 'User'
end

The Model spec is:

require 'spec_helper'

describe Document do
   describe 'associations' do
    it { should have_many(:folders).dependent(:destroy) }
    it { should belong_to(:project) }
    it { should belong_to(:author).class_name('User') }
  end
end

Stack Details

  • Ubuntu 22.04.2 LTS
  • Rails 5.2.2
  • Rspec 3.8.0
  • Shoulda-matchers 3.1.3
  • FactoryGirl 4.9.0

As a workaround, I've set the test subject to an instance of the Document class, with the parameters passed to the overridden new method.

This works but, doesn't use the defined factories of FactoryGirl.

I'm expecting to use FactoryGirl and provide custom parameters to the test subject using the defined factory.


Solution

  • You can use initialize_with and modify the document factory as follows:

    FactoryBot.define do
      factory :document do
        project
        author factory: :user
        # other attributes for document
    
        initialize_with { new(custom_arg_value) } # replace custom_arg_value with your value
      end
    end