1
我可以有我的联想搞砸了。我有以下模型:User和UserProfiles。Ruby on Rails的3:HAS_ONE协会测试
我的模型:
class User < ActiveRecord::Base
has_one :user_profile, :dependent => :destroy
attr_accessible :email
end
class UserProfile < ActiveRecord::Base
belongs_to :user
end
我有一个在我的user_profiles表命名为 “user_ID的” 栏。
我厂是建立像这样:
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
我user_spec测试设置像这样:
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
我user_profile_spec是设置像这样:
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
当我运行测试我得到“未定义的方法`user_profiles'为#”。我的测试有什么缺陷或者我的关系有缺陷?
谢谢!
我明白了。当我改变它,我得到“1)有效的属性 故障/错误应用户配置创建一个新的实例:!@ user.user_profile.create(@ attr)使用 NoMethodError: 未定义的方法'创建”对于零:NilClass #./spec/models/user_profile_spec.rb:32:in'块(2级)在<顶部(必需)>'” – Mike
为了创建的关联,你将要使用'create_user_profile'。而不是'user_profile.create'。 'association.create'方法用于基于集合的关联,'has_many'等。 – nowk