Ruby on Rails 3:has_one关联测试

时间:2011-09-20 01:16:18

标签: ruby-on-rails-3 rspec

我的关联可能搞砸了。我有以下模型:User和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”的列。

我的工厂设置如下:

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测试设置如下:

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'for#”。我的测试有何缺陷或我的关系存在缺陷?

谢谢!

1 个答案:

答案 0 :(得分:3)

您有一个名为has_one的{​​{1}}关联(单数)。您没有名为user_profile(复数)的关联。