Moriarty
Moriarty

Reputation: 159

How to define two new attributes in a factory which is defined inside another factory in RSpec?

I have two models named Student and Teacher. Both of them have same fields like name, age etc. Except Teacher has two extra attributes qualification and college. Now for writing rspec, I decided to created factories for the same as below:


FactoryGirl.define do
  factory :student do
    type 'student'

    factory :teacher do
      type 'teacher'
      qualification BA
      college XYZ
    end
  end
end

I defined the teacher inside student because both of them have same attributes except teacher has two extra attributes. I added the attributes as above, but it gave error as:


  1) Teacher#default_value_for 
     Failure/Error: it { expect(subject.qualification).to be_false}

     NoMethodError:
       undefined method `qualification' for #Student:0x0000000e8c0088'

Finished in 1.75 seconds (files took 14.48 seconds to load)
1 example, 1 failure

How to add those attributes in Teacher factory?

Thanks

Upvotes: 1

Views: 225

Answers (2)

Moriarty
Moriarty

Reputation: 159

I resolved the above issue by removing the nesting in the factories.


FactoryGirl.define do
  factory :student do
    type 'student'
  end

 factory :teacher do
   type 'teacher'
   qualification BA
   college XYZ
 end
end

This created two different factories in the same factory. :)

Upvotes: 0

Sovalina
Sovalina

Reputation: 5609

If your Student and Teacher models are 2 different classes without inheritance, you can't do what you're trying to achieve.

According to the FactoryBot source:

You can easily create multiple factories for the same class without repeating common attributes by nesting factories

factory :post do
  title { "A title" }

  factory :approved_post do
    approved { true }
  end
end

You can actually write nested factories if Teacher inherits the Student class.
Example here: how to define factories with a inheritance user model

Upvotes: 1

Related Questions