Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Undefined method 'name' in 'user' factory OR Undefined Method for all factories

I am currently using RSpec and Factory_Bot_Rails gems for testing an application, but I am running into the issue below.

When using factory_bot_rails version 5.0.2 gem, my factories now all give me an Undefined Method error for all my registered factories. If I downgrade the version of the gem to 4.11 it works.

For example for my users factory, which has name as one of the defined attributes, it displays the error

Undefined method 'name' in 'user' factory

I have tried so hard to fix this issue but it's not been feasible.

Any form of help will be highly appreciated.

like image 703
Promise Preston Avatar asked Sep 06 '25 20:09

Promise Preston


1 Answers

Here's how I solved the issue

From the blog by Thoughtbot, I came to realize that statically defined attributes have been deprecated and then removed from factory_bot >= 5.0. And so rather than use statically defined attributes for your factories, use dynamically defined attributes. That is, insert curly brackets {} around every defined attribute in your factory

Here's an example

Use Dynamically defined attributes

factory :robot do
  name { "Ralph" }
  email { "[email protected]" }
end

And not statically defined attributes

factory :robot do
  name "Ralph"
  email  "[email protected]"
end

You can read up more about it here

Deprecating static attributes in factory_bot 4.11

like image 176
Promise Preston Avatar answered Sep 08 '25 12:09

Promise Preston