I'm trying to Factory a Post associated with a Vote. So that Post.votes would generate the Vote's that are associated with it.
Factory.define :voted_post, :parent => :post, :class => Post do |p|
p.association :votes, :factory => :vote
end
And my rspec2 is relatively straightforward :
describe "vote scores" do
it "should show me the total vote score" do
@post = Factory(:voted_post)
@post.vote_score.should == 1
end
end
So why would it return this error :
Failures:
1) Post vote scores should show me the total vote score
Failure/Error: @post = Factory(:voted_post)
undefined method `each' for #<Vote:0x105819948>
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
Rails 3.0.0
Factory.define :voted_post, :parent => :post, :class => Post do |p|
p.association :votes, :factory => :vote
end
Is the same as trying to go
some_voted_post.votes = Factory(:vote)
Basically you're attempting to assign a single vote as an array.
EDIT
You can have an array containing a single vote, but you can't just have a single vote.
It's the difference between:
some_voted_post.votes = Factory(:vote)
and
some_voted_post.votes = [Factory(:vote)]
The former is not an array, and therefore does not work, the latter is an array.
If you want to assign has_many association which expects array and not a single value, you should use the long form:
Factory.define :voted_post, :parent => :post, :class => Post do |p|
p.votes { |vote| [vote.association(:vote)] }
end
And encapsulate the creation of the association with [] to ensure that array would be returned
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With