Factory Girl + Rspec:ArgumentError:参数数量错误(0表示2)

时间:2013-07-21 08:39:45

标签: ruby rspec tdd factory-bot

我有一个简单的餐厅课程,如下所示:

module Restaurant
    class Identity

        attr_reader :name, :location

        def initialize (name, location)
            @name = name
            @location = location
        end

    end
end

我的工厂看起来像这样:

FactoryGirl.define  do
    factory :restaurant, :class => Restaurant::Identity do |f|
        f.name "Alfredos"
        f.location "Andheri"
    end
end

我的测试是这样写的:

describe Restaurant::Identity do

 subject { build(:restaurant) }

 its(:name) {should_not be_nil}
 its(:location) {should_not be_nil}

end

但是当我跑这个时,我得到了

  1) Restaurant::Identity name 
     Failure/Error: subject { build(:restaurant) }
     ArgumentError:
       wrong number of arguments (0 for 2)
     # ./lib/restaurant.rb:7:in `initialize'
     # ./spec/restaurant_spec.rb:9:in `block (2 levels) in <top (required)>'
     # ./spec/restaurant_spec.rb:11:in `block (2 levels) in <top (required)>'

为什么会这样?我做错了什么?

1 个答案:

答案 0 :(得分:4)

好的,所以解决方法是在你的工厂女孩​​设置中使用initialize_with

FactoryGirl.define  do
    factory :restaurant, :class => Restaurant::Identity do |f|
        f.name "Alfredos"
        f.location "Andheri"
        initialize_with { new(name, location) } # add this line
    end
end

参考:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#custom-construction