Я определил эти 3 модели в Rails3.
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