issue with factory_girl , rpsec 2.0 and rails 3.0 => can't get has_one relation working nicely together!
I'm running rails 3.0, rspec 2.0 and factory_girl. Here is the simplified scenario I'm working with: a user can subscribe to only one plan at a time
# user.rb
class User < ActiveRecord::Base
has_one :plan
attr_accessible :login, :plan_id
end
# plan.rb
class Profile < ActiveRecord::Base
attr_accessible :plan
end
# user_factory.rb
Factory.define :user do |u|
u.login "test"
u.association :plan
end
#plan_factory.rb
Factory.define :plan do |p|
p.name "plan1"
end
when I run rspec spec/models/user_spec.rb I got this error:
Failure/Error: user = Factory(:user) SQLite3::ConstraintException: users.plan_id may not be NULL
#spec/models/user_spec.rb
require File.dirname开发者_如何学Go(__FILE__) + '/../spec_helper'
describe User do
it "should be valid" do
user = Factory(:user)
#User.new.should be_valid
user.should be_valid
end
end
what I'm doing wrong? I'm stuck with this very simple scenario, and it is very frustating. at that point BDD slow me down like hell!
It looks like you've implemented the has_one
association incorrectly. The foreign key in a has_one -- belongs_to
relationship should go in the table corresponding to the model with the belongs_to
directive. Check db/schema.rb
-- I think you'll find that plan_id
is defined in the users
table. If you want the User
model to have one Plan
, you'll need to remove plan_id
from users
and add user_id
to plans
.
If you'd rather make it so a Plan
has one User
, keep the schema as is and put has_one :user
in Plan
and belongs_to :plan
in User
.
A user subscribes to one plan. so a user has one plan and a plan is related to many users. So I think I got it right. the error was in the user factory. replacing
u.association :plan
by
u.association :plan, :factory => :plan
fixed the issue.
Problem solved!
精彩评论