Skip to content

Instantly share code, notes, and snippets.

@FlaviuSim
Created September 17, 2011 16:10
Show Gist options
  • Save FlaviuSim/1224087 to your computer and use it in GitHub Desktop.
Save FlaviuSim/1224087 to your computer and use it in GitHub Desktop.
factory_girl association recursion
# Question model - question.rb
class Question < ActiveRecord::Base
attr_accessible :text, :survey_id
belongs_to :survey
validates_presence_of :text, :survey
end
#Survey model - survey.rb
class Survey < ActiveRecord::Base
attr_accessible :name
has_many :questions, :dependent => :destroy
validates :name, :presence => true
end
#factories.rb
factory :question do
text "Who doesn't love the rubies?"
association :survey, :factory => :survey
end
factory :survey do
name 'Survey 1'
after_build do |s|
2.times { s.questions.build(FactoryGirl.attributes_for(:question)) }
end
end
end
# Model tests - question_spec.rb
it "should require a non-blank text" do
FactoryGirl.build(:question, :text => " ").should_not be_valid
end
#rspec error:
Question validation should require a non-blank text
Failure/Error: FactoryGirl.build(:question, :text => " ").should_not be_valid
ActiveRecord::RecordInvalid:
Validation failed: Questions survey can't be blank
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment