使用回调的Factorygirl错误:错误的参数数量

时间:2013-06-16 17:02:46

标签: ruby-on-rails rspec tdd factory-bot

您好,感谢您的阅读。这是我的工厂:

FactoryGirl.define do
  factory :venue do
    sequence(:name) { |n| "ExampleVenue#{n}" }

    factory :venue_with_gig do
      after_create do |venue|
        create(:gig, venue: venue)               #I've created a valid gig factory as well
      end                                        
    end
  end
end 

场地有很多演出和演出属于场地。我在这里看到它似乎遵循思想机器人blog post here

上的示例

然而,由于以下错误wrong Number of Arguments (3 for 2) at the之前的操作,我运行了我的模型规范并导致失败:

要求'spec_helper'

describe Venue do
  describe "basic attributes" do
    before { @venue = create(:venue_with_gig) }

    subject { @venue }

    it { should be_valid }
    it { should respond_to(:name) }
    # it { should respond_to(:address) }
    it { should respond_to(:gigs) }
  end 

  describe "with invalid params" do
    before { @venue = build(:venue, name: " ") }
    subject { @venue }

    it { should_not be_valid }
  end
end

我已经看了太久了,可以使用全新的视角。谢谢!

1 个答案:

答案 0 :(得分:1)

由于场地可能会演出,所以有必要定义你在说“venue_with_gig”时所需的演出,其中一个更好的名字是“venue_with_gigs”。您还需要使用create_list

# under venue define as your code
factory :venue_with_gigs do
  ignore do
    gigs_count 3 # Let's say 3 gigs as default
  end

  after(:create) do |venue, evaluator|
    FactoryGirl.create_list(:gig, evaluator.gigs_count, venue: venue)
  end                                        
end

默认使用

FactoryGirl.create(:venue_with_gigs)
# => 1 venue and 3 gigs created. Gigs under the venue

自定义数量

FactoryGirl.create(:venue_with_gigs, gigs_count: 10)
# => 1 venue 10 gigs created