CanCan + Factory_Girl - 奇怪的行为

时间:2012-04-16 23:08:00

标签: ruby-on-rails ruby-on-rails-3 factory-bot cancan

我有两个工厂 - 用户和公司。

FactoryGirl.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@exyzample.com" }
    password "secret"
    password_confirmation "secret"
  end

  factory :customer, :parent => :user do
    role "customer"
  end

  factory :company do
    name "User Company"
    association :user, :factory => :customer
  end
end

然后,当我从工厂创建公司时 - 一切都很完美,记录保存到数据库并与用户关联。很酷,但是当我试图测试用户能力时 - 我所有的测试都会失败。

有一个例子(rails console):

company = Factory(:company)
=> COMMIT
Ability.new(company.user)
=> Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

但是

company.user 
=> #<User id: 1, email: "user1@example.com", ..., role: "customer"> 

Ability.new(User.find(1))
=> #<Ability:0xcf6771c> ...

我很困惑。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你能告诉我用户的初始化方法吗?我认为这个问题出现是因为你没有在用户或公司工厂中定义一些关联