Factory Girl使用多个覆盖属性

时间:2014-09-12 09:50:01

标签: ruby-on-rails factory-bot

我有一个简单的工厂,目前定义为:

factory :tm_event do
    ...
    category "MyString"
    category_id { Random.rand(1..2147483647) }
    ...
end

我尝试使用以下内容创建TmEvent对象:

FactoryGirl.create(:tm_event, category: 'rock', category_id: '12')

运行此操作时,category和category_id在结果对象中都设置为nil

如果我使用单独设置的category或category_id运行,则设置两个实例并覆盖相应的属性。当我直接创建一个事件TmEvent.create(category: 'rock', category_id:'12')时,就会填充这两个属性。

我的语法是否正确? 我应该在哪里寻找解决方案?

1 个答案:

答案 0 :(得分:1)

你的语法似乎正确。我刚刚在我的控制台中尝试了相同的操作。它会更新这两个属性。

2.1.2 :010 >   FactoryGirl.build(:user)
 => #<User id: nil, email: "example@example.com", encrypted_password: "$2a$10$WnXKcpKZt0kkkXyRRe/QP.NS7mIaFcgFzCpZhW0hzEO...", 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, god: nil, name: "Test User 123", sash_id: nil, level: 0, confirmation_token: nil, confirmed_at: "2014-09-12 11:58:28", confirmation_sent_at: nil, unconfirmed_email: nil, failed_attempts: 0, unlock_token: nil, locked_at: nil>
2.1.2 :011 > FactoryGirl.build(:user, email: '123', sign_in_count: 2)
 => #<User id: nil, email: "123", encrypted_password: "$2a$10$JIjhQp40Lz/2fCskW63lzOHHxV2NwX2h5URswbuZsgH...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 2, 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, god: nil, name: "Test User 123", sash_id: nil, level: 0, confirmation_token: nil, confirmed_at: "2014-09-12 11:58:28", confirmation_sent_at: nil, unconfirmed_email: nil, failed_attempts: 0, unlock_token: nil, locked_at: nil>
2.1.2 :012 >

在您的控制台中试用。