RSpec 没有 rails 没有加载 spec/support 中的文件

RSpec without rails not loading files in spec/support

在文件spec/support/factory_girl.rb中我有

fail "At least this file is being required"

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

我有一些规范代码

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

但是当我 运行 bundle exec rspec 我得到

  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)>'

我假设 rspec 没有要求 spec/support/factory_girl.rb,即使 factory girl getting started guide 说我应该把文件放在那里。

当我开始项目时,我有 运行 命令行命令来初始化 rspec,那是在我为项目使用 factory girl 之前。

为什么 RSpec 不加载 spec/support 中的文件?

尽管 FactoryGirl 指南建议在 support/factory_girl.rb 中配置 RSpec,您仍然需要手动要求该文件。我建议将以下内容添加到您的 spec_helper:

require 'factory_girl' # require the gem
require_relative './support/factory_girl' # this should point to the factory_girl.rb file.

spec/support 没什么神奇的。如果你使用 rspec-rails 那么它过去常常添加一行自动加载那里的所有东西但是从 3.1.0 开始它没有 - 看到这个 commit).

我只能假设工厂女孩文档假设存在这个现已停用的功能。您可以通过添加

为您的项目启用此功能
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

给您的规范助手,或者您当然可以将 config.include 行移动到主 spec_helper 文件中。

在非 rails 世界中,将 Rails.root 替换为项目根所在的位置。