我将 rolify 与用户模型和任务模型(Rails 4)一起使用。用户可以拥有的角色之一是“所有者”。我想使用 Factory Girl 创建一个用户对象并为其分配一个角色。这是我的工厂:
FactoryGirl.define do
factory :task do
owner "Steve"
agency "an agency"
facility "a facility"
description "This task must absolutely be done"
due_date "2013-12-22 03:57:37"
completed_date "2013-12-22 03:57:37"
factory :task_with_owner do
ignore do
user_id nil
end
after(:create) do |task, user_id|
User.find(user_id).add_role :owner, task
end
end
end
end
该规范通过:
it 'is capable of creating a valid object with owner' do
@user = create(:user)
task = create(:task_with_owner, user_id: @user.id)
expect(@user.has_role? :owner, task).to be_true
end
此规范失败:
it 'is capable of creating two valid objects with an owner' do
@user = create(:user, username: 'janeblow')
task = create(:task_with_owner, user_id: @user.id)
expect(@user.has_role? :owner, task).to be_true
task = create(:task_with_owner, user_id: @user.id)
expect(@user.has_role? :owner, task).to be_true
end
错误是:
Failure/Error: task = create(:task_with_owner, user_id: @user.id)
ActiveRecord::RecordNotFound:
Couldn't find User with id=#<#<Class:0x000000050f5e10>:0x00000004c9ed08>
# ./spec/factories/tasks.rb:19:in `block (4 levels) in <top (required)>'
# ./spec/models/role_spec.rb:15:in `block (2 levels) in <top (required)>'
为什么?