RSpec与FactoryGirl没有Rails - 它在哪里寻找模型?

时间:2016-10-11 14:43:38

标签: ruby activerecord rspec

我正在编写不使用Rails的ActiveRecord Ruby应用程序。我想用FactoryGirl测试模型,但我正在努力配置。鉴于未初始化的常量错误,我猜它无法在lib/models文件夹中找到模型。

我想知道rspec / FactoryGirl期望的文件夹结构,或者如何通知它有关模型的位置。

rspec -fd spec / models / user_spec.rb
…/spec/models/user_spec.rb:3:in `<top (required)>': uninitialized constant User (NameError)
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:100:in `setup'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:86:in `run'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:71:in `run'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:45:in `invoke'
    from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/exe/rspec:4:in `<top (required)>'
    from ./bin/rspec:17:in `load'
    from ./bin/rspec:17:in `<main>'
规格/型号/ user.rb
describe User, type: :model do
  it 'can be instantiated' do
    user = User.new
    expect(user).to be_a User
  end
end
LIB /模型/ user.rb
class User < ActiveRecord::Base
end

我使用rspec --init创建了RSpec配置:

.rspec
--color
--require spec_helper
投机/ spec_helper.rb
require 'factory_girl'
require_relative 'support/factory_girl'

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups

end
规格/支持/ factory_girl.rb
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods

  config.before(:suite) do
    FactoryGirl.find_definitions
  end
end
投机/ factories.rb
FactoryGirl.define do
  factory :user do
    username "johnny"
  end
end

1 个答案:

答案 0 :(得分:0)

您缺少的部分是Rails在运行RSpec测试套件时从spec_helper.rb加载FactoryGirl之前的所有模型。

尝试在spec_helper.rb

的顶部加载所有模型
root = File.expand_path('../', File.dirname(__FILE__))
Dir[File.join(root,'lib/**/*.rb')].each { |f| require f }

require 'factory_girl'
require_relative 'support/factory_girl'

...