问题
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!!
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/48091582/ruby-gem-uninitialized-constant-factorybot