'"Undefined method `build'" when using Rspec + FactoryBotRails

I'm trying this gem called FactoryBotRails. For some reason, when I try it on one of my models unit tests, the following error is thrown.

Failure/Error: my_model = build(:my_model)
NoMethodError:
undefined method `build' for #\<\RSpec::ExampleGroups::MyModel::ValidationTests:0x000055c553959958>

I don't know what I'm doing wrong, as long as I have followed several tutorials on the web, and did the same steps.


Added, in:

gemfile

gem 'factory_bot_rails', '~> 5.1.1'

app/spec/support/factory_bot.rb

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

spec/rails_helper.rb

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

spec/factories/my_models.rb

FactoryBot.define do
  factory :my_model do
    name { 'some name' }
    code { 'some code' }
  end
end

And used it like:

my_model = build(:my_model)

What is wrong with my configuration?



Solution 1:[1]

The issue might not be what you're calling, but where you're calling it. my_model = build(:my_model) is not syntax you want to use while writing specs, and the error message looks maybe you're calling it from outside of a spec? Because if you're calling it from within a spec, the error should be something along the lines of ArgumentError: Factory not registered: my_model. The spec itself should look like this:

# spec/models/my_model_spec.rb
require 'rails_helper'

describe MyModel do
  let(:my_model) { build :my_model }

  it { expect(my_model).to be_valid }
end

I would also specify the model name in your factory declaration (i.e., factory :my_model, class: 'MyModel' do). If you want to play with your factories, you can start up a test console:

# start rails console in 'test' environment
rails console test
my_model = FactoryBot.build :my_model

Note that you will need to use FactoryBot.build instead of build in your test console.

If this doesn't resolve your issue, please update your post with the contents of the spec you're trying to run, how you're trying to run it, and expand your definition of your spec/rails_helper.rb file. Since you're new to RSpec, I also suggest checking out http://www.betterspecs.org/ for best practices.

Solution 2:[2]

The syntax for creation of factorybot is:

FactoryBot.create :my_model

Pass arguments hash if you need something different:

FactoryBot.create :my_model, name: "John Doe"

For multiple (e.g. 10 my_models):

FactoryBot.create_list :my_model, 10

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allison
Solution 2