Ruby on Rails 3:has_one 关联测试 [英] Ruby on Rails 3: has_one association testing
问题描述
我可能把我的联想搞砸了.我有以下模型:User 和 UserProfiles.
I may have my associations messed up. I have the following models: User and UserProfiles.
我的模型:
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"的列.
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 "test@test.com"
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 测试设置如下:
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
我的 user_profile_spec 设置如下:
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
当我运行测试时,我得到# 的未定义方法`user_profiles'".我的测试有什么问题,还是我的关系有问题?
When I run the tests I get "undefined method `user_profiles' for #". How is my test flawed or is my relationship flawed?
谢谢!
推荐答案
您有一个名为 user_profile
(单数)的 has_one
关联.您没有名为 user_profiles
(复数)的关联.
You have a has_one
association called user_profile
(singular). You do not have an association called user_profiles
(plural).
这篇关于Ruby on Rails 3:has_one 关联测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!