I am new to testing and factory_girl, and I want to create factories using factory_girl for a has_many through association.
I have seen a lot of articles on the web, but couldn't see the best way to do it. I have two models,Widget
and Feature
.
The associations are:
class Feature < ActiveRecord::Base
has_many :widget_features
has_many :widgets, :through => :widget_features
end
and
class Widget < ActiveRecord::Base
has_many :widget_features
has_many :features, :through => :widget_features
end
Till now, I have tried this:
- In my widget_feature_spec.rb, I did this
require '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
and many factories are
Factory.define :feature do |f|
f.name "Feature_name"
f.description "Feature_description"
f.association :widget
end
and
Factory.de开发者_如何学Gofine :widget do |f|
f.sequence(:title) {|n| "Widget_title#{n}"}
end
But autotest fails, giving this error:
NoMethodError:undefined method `widget_id=' for #
Then, if I add
f.widget_id Factory.create(:widget).id
to my Feature factories, I get this error,
/factory_girl/factory.rb:334:in `factory_by_name': No such factory: widget (ArgumentError)
I don't know what to do. I believe I am not getting it right. What is the best way to create factories for such associations.
Should I create associations inWidgetFeature
OR Wigdet
and Feature
??Try to change the line:
10.times { |i| Factory.create(:feature, :widget_id => widget.id)}
into
10.times { |i| Factory.create(:feature, :widget => widget)}
精彩评论