Anas Shahid
Anas Shahid

Reputation: 3

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

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.

Upvotes: -1

Views: 42

Answers (1)

piowit
piowit

Reputation: 51

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

Upvotes: 1

Related Questions