【问题标题】:Setting FactoryGirl and use it in Grape and RSpec?设置 FactoryGirl 并在 Grape 和 RSpec 中使用它?
【发布时间】:2015-07-21 16:38:24
【问题描述】:

在我的 Grape ruby​​ 项目中。我将我的模型分离为一个 gem,这样我就可以在我的 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:

【问题讨论】:

  • 请注意,我使用的是 FactoryGirl(不是 rails 版本)
  • 应该build(:member, first_name: 'Eki', last_name: 'Eqbal')build(:user, first_name: 'Eki', last_name: 'Eqbal')

标签: ruby testing rspec factory-bot


【解决方案1】:

代替:

factory :user do

试试:

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

FactoryGirl 根据工厂名称猜测类名,所以如果它在这样的模块中,它不会找到它。

【讨论】:

  • 你就是 @Nick 的人 :) 这正是我想要的。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多