Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `each' in a factory_girl / rspec2 scenario

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

like image 589
Trip Avatar asked Sep 21 '10 02:09

Trip


2 Answers

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.

like image 181
Jamie Wong Avatar answered Sep 27 '22 02:09

Jamie Wong


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

like image 33
edzhelyov Avatar answered Sep 24 '22 02:09

edzhelyov