0
我在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
下面是投机/ 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
在它的脸上,这看起来没错。你有没有尝试添加一个'调试器'? –
你在哪里创建'@ question'实例,你能显示那个代码吗? – rdvdijk
我从来没有使用调试器,不知道如何使用它。你知道有什么资源可以学习吗? –