FactoryGirl 方法不起作用

FactoryGirl methods not working

我正在使用 RSpec 和 Capybara 测试 Rails 应用程序。我也决定使用 FactoryGirl。我将这一行添加到我的 Gemfile 和 运行 bundle install:

gem 'factory_girl_rails'

根据 FactoryGirl GitHub 页面上的说明,我还将此行添加到 spec/support/factory_girl.rb:

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

我在spec/factories.rb中添加了一些工厂:

FactoryGirl.define do
  factory :trip_plan do
    title "A New Plan"
    day 15
  end
end

我的rails_helper.rb(没有大量评论):

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
end

但现在当我尝试 运行 我的模型规范中的 FactoryGirl 方法时(在 spec/models/trip_plan_spec.rb 中),例如:

require 'rails_helper'

RSpec.describe TripPlan, type: :model do
  describe 'the day validation process' do
    it 'validates that day in between 1 and 365' do
      t1 = create(:trip_plan)
      # Some more validations here...
    end
  end
end

我收到一条错误消息 undefined method 'create'。我将如何解决这个问题?

您在 rails_helper.rb 配置中错过了这一行:

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }

负责读取您的 support 文件,例如 factory_girl.rb