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
我從來沒有使用調試器,不知道如何使用它。你知道有什麼資源可以學習嗎? –