FactoryGirl在枚举状态字段

时间:2016-07-13 09:36:34

标签: factory-bot ruby-on-rails-4.2

我正在尝试为Client.rb模型构建FactoryGirl工厂:

Client.rb

  enum status: [ :unregistered, :registered ]

 has_many :quotation_requests

  #Validations

  validates :first_name, 
            presence: true,
            length: {minimum: 2}

  validates :last_name, 
            presence: true,
            length: {minimum: 2}

  validates :email, email: true

  validates :status, presence: true

厂:

FactoryGirl.define do
  factory :client do
    first_name "Peter"
    last_name "Johnson"
    sequence(:email) { |n| "peterjohnson#{n}@example.com" }
    password "somepassword"
    status "unregistered"
  end
end

client_spec.rb

    require 'rails_helper'

    RSpec.describe Client, type: :model do

        describe 'factory' do

          it "has a valid factory" do
            expect(FactoryGirl.build(:client).to be_valid
          end

        end
end

我收到以下错误

  1) Client factory has a valid factory
     Failure/Error: expect(FactoryGirl.build(:client, status: 'unregistered')).to be_valid
       expected #<Client id: nil, email: "peterjohnson1@example.com", encrypted_password: "$2a$04$urndfdXNfKVqYB5t3kERZ.c.DUitIVXEZ6f19FNYZ2C...", first_name: "Peter", last_name: "Johnson", status: "0", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil> to be valid, but got errors: Status can't be blank

错误是状态不能为空。

我不明白这是怎么可能的,因为工厂明确地为status属性赋值。

如何让这个工厂构建一个有效的客户端对象?

Rails 4.2 使用factory_girl 4.7.0 使用factory_girl_rails 4.7.0

2 个答案:

答案 0 :(得分:1)

此错误是由我用于status属性的数据类型引起的。我选择了字符串而不是整数。

我通过运行新迁移来解决问题,将状态的数据类型更改为整数。

"Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
  "version": "1.0.0-preview2-final",
  "imports": [
    "portable-net45+win8"
  ]
}

现在它完美无缺。

答案 1 :(得分:0)

我想你忘记了

let(:client) { FactoryGirl.create(:client) }

在client_spec.rb上

您在哪里创建客户端对象?

其他问题可能是您在工厂分配:

status "unregistered"

而不是:

  

状态:未注册

作为符号或由于是枚举,也许你应该做

  

状态0#:未注册