开发者

Trouble on initializing a factory object

开发者 https://www.devze.com 2023-04-09 15:32 出处:网络
I am using Ruby on Rails 3.1.0, rspec-rails 2 and Factory gems. I have some trouble related to the validation process when I state a Factory object 开发者_开发知识库for an Account class.

I am using Ruby on Rails 3.1.0, rspec-rails 2 and Factory gems. I have some trouble related to the validation process when I state a Factory object 开发者_开发知识库for an Account class.

In the model file I have:

class Account < ActiveRecord::Base
  belongs_to :user

  attr_accessible :name, ..., :password

  validates :name,
    :presence => true

  ...

  validates :password,
    :presence => true
end

In the factory file I have:

FactoryGirl.define do
  factory :account, do
    sequence(:name)  { |n| "Foo #{n}"}
    ...
    password 'psw_secret'
    association :user
  end

  factory :user do
    auth 'registered'
  end
end

When in the spec file I state let!(:account) { Factory(:account) } it works as expected but when I use the following:

let!(:user) { Factory(:user, :account => Factory(:account)) }

I get this error:

Failure/Error: let!(:user) { Factory(:user, :account => Factory(:account)) }
ActiveRecord::RecordInvalid:
   Validation failed: Account password can not be blank, Account is invalid

Why I get that error? How can I solve the problem?


I think you should do it the other way around:

@user = Factory(:user)
@account = Factory(:account, :user => @user)

The relation is defined on account, not on user. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消