Reputation: 2601
I may have my associations messed up. I have the following models: User and UserProfiles.
My models:
class User < ActiveRecord::Base
has_one :user_profile, :dependent => :destroy
attr_accessible :email
end
class UserProfile < ActiveRecord::Base
belongs_to :user
end
I have a column named "user_id" in my user_profiles table.
My factory is setup like so:
Factory.define :user do |user|
user.email "[email protected]"
end
Factory.sequence :email do |n|
"person-#{n}@example.com"
end
Factory.define :user_profile do |user_profile|
user_profile.address_line_1 "123 Test St"
user_profile.city "Atlanta"
user_profile.state "GA"
user_profile.zip_code "30309"
user_profile.association :user
end
My user_spec test is setup like so:
describe "profile" do
before(:each) do
@user = User.create(@attr)
@profile = Factory(:user_profile, :user => @user, :created_at => 1.day.ago)
end
it "should have a user profile attribute" do
@user.should respond_to(:user_profile)
end
it "should have the right user profile" do
@user.user_profile.should == @profile
end
it "should destroy associated profile" do
@user.destroy
[@profile].each do |user_profile|
lambda do
UserProfile.find(user_profile)
end.should raise_error(ActiveRecord::RecordNotFound)
end
end
end
My user_profile_spec is setup like so:
describe UserProfile do
before(:each) do
@user = Factory(:user)
@attr = { :state => "GA" }
end
it "should create a new instance with valid attributes" do
@user.user_profiles.create!(@attr)
end
describe "user associations" do
before(:each) do
@user_profile = @user.user_profiles.create(@attr)
end
it "should have a user attribute" do
@user_profile.should respond_to(:user)
end
it "should have the right associated user" do
@user_profile.user_id.should == @user.id
@user_profile.user.should == @user
end
end
end
When I run the tests I get "undefined method `user_profiles' for #". How is my test flawed or is my relationship flawed?
Thanks!
Upvotes: 1
Views: 3540
Reputation: 33161
You have a has_one
association called user_profile
(singular). You do not have an association called user_profiles
(plural).
Upvotes: 3