-1

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.

  • You can access the parameters of a factory with `attributes_for :factory_name`. – smathy Aug 07 '23 at 20:27
  • 1
    `new` is not just an ActiveRecord method but a Ruby method. I try to not give answers which tell people that their approach is wrong, but in this case I have to go with "don't override new". – Archonic Aug 07 '23 at 21:45
  • @Archonic - I do know about `new`. Yes, I agree about avoiding to override new. It's just legacy code that I can't update for the time being. – Anas Shahid Aug 08 '23 at 11:08

1 Answers1

1

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
piowit
  • 51
  • 4