如何使用多个关联构建Active Record?

时间:2012-01-21 21:41:35

标签: ruby-on-rails-3 activerecord

我在Rails3中定义了这3个模型。

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers

class Question < ActiveRecord::Base
  belongs_to :user
  has_many :answers

class Answer < ActiveRecord::Base
  belongs_to :user
  belongs_to :question

我写了这样的RSpec:

describe "user associations" do
  before :each do
    @answer = @user.answers.build question: @question
  end

  it "should have the right associated user" do
    @answer.user.should_not be_nil
  end

  it "should have the right associated question" do
    @question.should_not be_nil
    @answer.question.should_not be_nil #FAIL!!
  end

但我总是收到以下错误:

Failures:

  1) Answer user associations should have the right associated question
     Failure/Error: @answer.question.should_not be_nil
       expected: not nil
            got: nil

我猜这一行是错误的:

@answer = @user.answers.build question: @question

但我应该如何建立答案对象?

更新:谢谢大家,我发现我应该这样写:

require 'spec_helper'

describe Answer do
  before :each do
    @user = Factory :user 
    asker = Factory :user, :user_name => 'someone'
    @question = Factory :question, :user => asker
  end

  describe "user associations" do
    before :each do
      @answer = Factory :answer, :user => @user, :question => @question
    end

    it "should have the right associated user" do
      @answer.user.should_not be_nil
    end

    it "should have the right associated question" do
      @answer.question.should_not be_nil
    end
  end
end

这是spec / factories.rb:

Factory.define :user do |user|
  user.user_name "junichiito"
end

Factory.define :question do |question|
  question.title "my question"
  question.content "How old are you?"
  question.association :user
end

Factory.define :answer do |answer|
  answer.content "I am thirteen."
  answer.association :user
  answer.association :question
end

1 个答案:

答案 0 :(得分:1)

一旦我明确保存@user实例,规范就不会再失败了。这是我的版本:

require 'spec_helper'

describe Answer do
  before :each do
    @user = User.new
    @user.save!
    @question = @user.questions.build 
    @question.save!

    @answer = @user.answers.build question: @question
    @question.answers << @answer
  end

  it "should have the right associated user" do
    @answer.user.should_not be_nil
  end

  it "should have the right associated question" do
    @question.should_not be_nil
    @answer.question.should_not be_nil # SUCCESS!
  end
end