factory_girl / rspec2场景中未定义的方法`each'

时间:2010-09-21 02:28:18

标签: ruby-on-rails ruby ruby-on-rails-3 factory-bot rspec2

我正在尝试生成与投票相关联的帖子。所以Post.votes会生成与之相关的投票。

Factory.define :voted_post, :parent => :post, :class => Post do |p|
  p.association :votes, :factory => :vote
end

我的rspec2相对简单:

describe "vote scores" do
  it "should show me the total vote score" do
    @post = Factory(:voted_post)
    @post.vote_score.should == 1
  end
end

那为什么会返回这个错误:

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

2 个答案:

答案 0 :(得分:12)

Factory.define :voted_post, :parent => :post, :class => Post do |p|
  p.association :votes, :factory => :vote
end

和尝试去一样

some_voted_post.votes = Factory(:vote)

基本上你是在尝试将一个投票分配为数组。

修改

您可以拥有一个包含单一投票的数组,但您不能只进行一次投票。

区别在于:

some_voted_post.votes = Factory(:vote)

some_voted_post.votes = [Factory(:vote)]

前者不是数组,因此不起作用,后者是数组。

答案 1 :(得分:5)

如果要分配需要数组而不是单个值的has_many关联,则应使用长格式:

Factory.define :voted_post, :parent => :post, :class => Post do |p|
  p.votes { |vote| [vote.association(:vote)] }
end

用[]封装与关联的创建,以确保返回数组