设置FactoryGirl并在Grape和RSpec中使用它?

时间:2015-07-21 16:38:25

标签: ruby testing rspec factory-bot

在我的Grape ruby​​项目中。我将我的模型分离到一个宝石,所以我可以在我的ruby项目之间使用它。

现在的问题是,通过我的主动记录,让我们说我正在处理User模型,现在它看起来像这样:

module MyApp
  module Core    
    class User < ActiveRecord::Base
      self.table_name = 'users'          
    end    
  end
end

我正在使用像这样的工厂女孩​​:

FactoryGirl.define do
  factory :user do

    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    email { Faker::Internet.email }
    password { "12345678" }
    password_confirmation { "12345678" }
  end
end

让我们说我有以下rspec测试:

require 'spec_helper'

describe MyApp::Core::User do
    it "has name assigned" do
      user = build(:member, first_name: 'Eki', last_name: 'Eqbal')
      expect(user.first_name).to eq('Eki')
      expect(user.last_name).to eq('Eqbal')
    end  
end

当我尝试运行测试时:

⇒  bundle exec rspec spec/unit/users_spec.rb
warning: parser/current is loading parser/ruby22, which recognizes
warning: 2.2.3-compliant syntax, but you are running 2.2.0.
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}
F

Failures:

  1) MyApp::Core::User has name assigned
     Failure/Error: user = build(:user, first_name: 'Eki', last_name: 'Eqbal')
     NameError:
       uninitialized constant User
     # ./spec/unit/users_spec.rb:37:in `block (2 levels) in <top (required)>'

Finished in 0.14788 seconds
1 example, 1 failure

Failed examples:

1 个答案:

答案 0 :(得分:2)

而不是:

factory :user do

尝试:

factory :user, class: MyApp::Core::User do

FactoryGirl根据工厂名称猜测班级名称,因此,如果它在类似的模块中,则无法找到它。