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"라는 이름의 열이.
내 공장과 같이 설정이다 : 나는 실행
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
:
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은과 같이 설정입니다 :
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 테스트 설정과 같이이다 내가 얻은 테스트는 "정의되지 않은 메소드`user_profiles 'for #"를 얻는다. 내 테스트에 결함이 있거나 내 관계에 결함이 있습니까?
감사합니다.
나는 본다. "1) UserProfile은 유효한 속성으로 새 인스턴스를 생성해야합니다. 오류/오류 : @ user.user_profile.create! (@ attr) NoMethodError : 'create!' nilClass # ./spec/models/user_profile_spec.rb:32 : in'top (필수)> '블록 (2 레벨)' " – Mike
연관을 생성하려면'create_user_profile'을 사용하십시오. 'user_profile.create' 대신에. 'association.create' 메쏘드는 콜렉션 기반 연관들,'has_many'와 같은 것입니다. – nowk