I defined these 3 models in 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
I wrote RSpec like this:
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
But I always get the following error:
Failures:
1) Answer user associations should have the right associated question
Failure/Error: @answer.question.should_not be_nil
expected: not nil
got: nil
I guess this line is wrong:
@answer = @user.answers.build question: @question
But how should I build answer object?
Update: Thanks everyone, I found I should have to write like this:
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
Here is 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
Once I explicitly save the
@userinstance, the spec doesn’t fail anymore. Here’s my version: