0

我不得不承认我是测试新手,所以我正在尝试我的前几个 Rspec 和 Factory Girl 测试。一切都很顺利,直到我尝试使用工厂女孩。

我的配置如下

规范/spec_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'database_cleaner'
require 'factory_girl_rails'

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

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"

  config.include FactoryGirl::Syntax::Methods

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end

规格/模型/role_spec.rb

require 'spec_helper'

describe Role do
  it "is valid" do
    role = FactoryGirl.build(:role)
    expect(role).to be_valid
  end
end

规格/工厂.rb

FactoryGirl.define do   
  factory :role do
    rolesymbol "tst-admin"
    name "test admin"
  end
end

但是,当我运行 bundle exec rspec 或 rake spec 时,出现以下错误

Failures:

  1) Role is valid
     Failure/Error: role = FactoryGirl.build(:role)
     ArgumentError:
       Factory not registered: role
     # ./spec/models/role_spec.rb:12:in `block (2 levels) in <top (required)>'

对我来说,FactoryGirl 似乎工作正常,角色定义正确,规范正常工作,所以我不知道发生了什么。有任何想法吗?

迈克尔

4

3 回答 3

1

我参加这个聚会有点晚了,但是当我尝试在 Rails 引擎中使用带有 RSpec 的 FactoryGirl 时遇到了同样的问题。我通过在我的 spec/spec_helper.rb 文件中明确设置工厂女孩定义路径解决了这个问题

FactoryGirl.definition_file_paths = [File.expand_path('../factories', __FILE__)]
FactoryGirl.find_definitions

目录结构如您所料:

root/
  spec/
    spec_helper.rb
    a_spec_file.rb
    factories/
      my_factory.rb

根据 FactoryGirl 文档,这种结构应该开箱即用(https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#defining-factories)。我还没有调查为什么对我来说不是这种情况。(第一次回复SO,如果这里有什么问题,请见谅!)

于 2013-09-30T15:35:10.580 回答
0

尝试将 require 'factory_girl' 添加到您的 factory.rb 中?

于 2013-04-17T16:13:25.843 回答
-1

我什至迟到了聚会,但我通过将factories目录移动到(现在)更标准的路径来解决这个问题spec/support/factories- rspec 现在可以将其拾取,而无需进一步告诉它在哪里查找。

于 2014-08-28T00:00:49.773 回答