【发布时间】:2011-06-22 07:47:51
【问题描述】:
我是 testing 和 factory_girl 的新手,我想通过关联创建使用 factory_girl 的工厂。
我在网上看过很多文章,但找不到最好的方法。
我有两个模型,Widget 和 Feature。
这些关联是:
class Feature < ActiveRecord::Base
has_many :widget_features
has_many :widgets, :through => :widget_features
end
和
class Widget < ActiveRecord::Base
has_many :widget_features
has_many :features, :through => :widget_features
end
到目前为止,我已经尝试过:
- 在我的 widget_feature_spec.rb 中,我这样做了
需要'spec_helper'
describe WidgetFeature do context "- METHOD - method_name " do it "should do blah" do widget = Factory.create(:widget) 10.times { |i| Factory.create(:feature, :widget_id => widget.id)} result = WidgetFeature.method_name(widget.id) # do all the checks and expectations now end end end
很多工厂都是
Factory.define :feature do |f|
f.name "Feature_name"
f.description "Feature_description"
f.association :widget
end
和
Factory.define :widget do |f|
f.sequence(:title) {|n| "Widget_title#{n}"}
end
但自动测试失败,出现此错误:
NoMethodError:undefined method `widget_id=' for #
那么,如果我添加
f.widget_id Factory.create(:widget).id
对于我的功能工厂,我收到此错误,
/factory_girl/factory.rb:334:in `factory_by_name': No such factory: widget (ArgumentError)
我不知道该怎么办。我相信我没有做对。为此类协会创建工厂的最佳方式是什么。
我应该在WidgetFeature 或Wigdet 和Feature 中创建关联吗??
【问题讨论】:
-
我假设您有一个未向我们展示的 widget_features 连接表,是吗?
标签: ruby-on-rails ruby-on-rails-3 associations has-many-through factory-bot