undefined method `each' in a factory_girl / rspec2 scenario
Asked Answered
P

2

5

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

Prosperus answered 21/9, 2010 at 2:28 Comment(0)
I
12
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.

Influenza answered 21/9, 2010 at 2:55 Comment(2)
Thanks Jamie! And I guess the alternative would be creating an incrementer sequencer in the factory itself.Prosperus
7 year old answer but saved me a lot of time. Thanks.Labors
S
5

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

Spandrel answered 28/7, 2011 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.