Reputation: 921
Working on a Ruby gem and trying to use FactoryBot inside with RSpec.
I have this in support/factory_bot.rb
:
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
FactoryBot.find_definitions
end
end
and in spec_helper.rb
:
require 'support/factory_bot'
When I try to run the spec rake task, I get this error:
support/factory_bot.rb:2:in `block in <top (required)>': uninitialized constant FactoryBot (NameError)
What am I missing? This used to work fine when I was using the old factory_girl gem, but it has broken with the rename to factory_bot. Thanks!!
Upvotes: 32
Views: 27494
Reputation: 6925
In my case I had to put those lines below 'require "rspec/rails"
in file:
spec/rails_helper.rb
:
like:
require "rspec/rails"
require_relative "support/factory_bot"
require_relative "support/chrome"
Upvotes: 0
Reputation: 51
I had this problem too, remove the
require 'support/factory_bot'
There's a line on rails_helper, just uncomment it:
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
Upvotes: 5
Reputation: 81
I had encountered and issue similar to this. I worked around it by removing the default testing suite ( MiniTest ). When you create a rails application and intend on using rspec and factory_bot, use the code below in the command line:
rails new myapp -T
Hope this helps xP
Upvotes: 0
Reputation: 8065
Overview just in case you are doing this from scratch
installation rspec
details here (basically add gem
to Gemfile
then run bundle install
)
initialize RSPEC
in your rails project rails g rspec:install
create new file your spec/support/factory_bot.rb
add the following base code:
require 'factory_bot'
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
# RSpec without Rails
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
FactoryBot.find_definitions
end
end
add reference on spec/rails_helper.rb
require 'support/factory_bot'
as well as remove any fixture
unused reference like this one
config.use_transactional_fixtures = true
That should be it!, finally run any spec
file you want inside rspec default folders
e.g.:
spec/features/my_action_spec.rb
spec/models/my_model_spec.rb
spec/task/my_task_spec.rb
or run them all and check depending on your setup
rspec
rails rspec
bundle exec rspec
hope this helps someone with the whole RSPEC
+ FactoryBot
Gem
installation process
Upvotes: 30
Reputation: 921
Doh. Silly mistake here, running bundle exec rake spec
instead of rake spec
solved it.
Also had to add require 'factory_bot'
to the top of support/factory_bot.rb
Upvotes: 44