我正在尝试为 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
我收到以下错误L
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
错误是"状态"不能为空。
我不明白这怎么可能,因为工厂清楚地为状态属性分配了一个值。
如何让此工厂生成有效的客户端对象?
导轨 4.2使用 factory_girl 4.7.0使用 factory_girl_rails 4.7.0
此错误是由我用于状态属性的数据类型引起的。我选择了字符串而不是整数。
我通过运行新的迁移将状态的数据类型更改为整数来解决问题。
class ChangeColumnTypeClientStatus < ActiveRecord::Migration
def change
change_column :clients, :status, :integer, default: 0
end
end
现在它完美运行。
我想你忘记了
let(:client) { FactoryGirl.create(:client) }
在您的client_spec.rb 上
在哪里创建客户端对象?
其他问题可能是您在工厂分配:
status "unregistered"
而不是:
状态 :未注册
作为一个符号或由于是一个枚举,也许你应该做
状态 0 # :未注册