问题
In the file spec/support/factory_girl.rb I have
fail "At least this file is being required"
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
and I have in some spec code
require 'pmc_article'
require 'pmc_article_parser'
require 'factory_girl'
require_relative './factories/pmc_article_factory'
RSpec.describe PMCArticle do
let(:pmc_article) do
build(:pmc_article)
end
it 'parses pmid' do
expect(pmc_article.article_id_pmid).to eq '123456'
end
end
but when I run bundle exec rspec
I get
1) PMCArticle parses pmid
Failure/Error: build(:pmc_article)
NoMethodError:
undefined method `build' for #<RSpec::ExampleGroups::PMCArticle:0x007feac3cc5078>
# ./spec/pmc_article_spec.rb:8:in `block (2 levels) in <top (required)>'
# ./spec/pmc_article_spec.rb:12:in `block (2 levels) in <top (required)>'
I assume that rspec is failing to require spec/support/factory_girl.rb
, even though the factory girl getting started guide says I should put the file there.
I had run the command line command to initialize rspec when I started the project, which was before I was using factory girl for the project.
Why isn't RSpec loading files in spec/support?
回答1:
There is nothing magic about spec/support. If you use rspec-rails then it used to add a line loading everything in there automatically but as of of 3.1.0 it doesn't - see this commit).
I can only assume that the factory girl docs assume the presence of this now deactivated feature. You can turn this on for your project by adding
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
To your spec helper or of course you could move that config.include
line into your main spec_helper file.
In a non rails world, replace Rails.root
with wherever the root of your project is.
回答2:
Though the FactoryGirl guide suggests configuring RSpec in support/factory_girl.rb, you still need to require that file manually. I recommend adding the following to your spec_helper:
require 'factory_girl' # require the gem
require_relative './support/factory_girl' # this should point to the factory_girl.rb file.
来源:https://stackoverflow.com/questions/29441808/rspec-without-rails-not-loading-files-in-spec-support