0

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

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)>'

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

4

1 回答 1

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

于 2013-07-21T09:03:30.593 回答