RSpec without rails not loading files in spec/support

心已入冬 提交于 2020-01-05 09:36:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!