Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl: attributes_for not giving me associated attributes

I have a Code model factory like this:

Factory.define :code do |f|
    f.value "code"
    f.association :code_type
    f.association(:codeable, :factory => :portfolio)
end

But when I test my controller with a simple test_should_create_code like this:

  test "should create code" do
    assert_difference('Code.count') do
      post :create, :code => Factory.attributes_for(:code)
    end
    assert_redirected_to code_path(assigns(:code))
  end

... the test fails. The new record is not created.

In the console, it seems that attributes_for does not return all required attributes like the create does.

rob@compy:~/dev/my_rails_app$ rails console test
Loading test environment (Rails 3.0.3)
irb(main):001:0> Factory.create(:code)
=> #<Code id: 1, code_type_id: 1, value: "code", codeable_id: 1, codeable_type: "Portfolio", created_at: "2011-02-24 10:42:20", updated_at: "2011-02-24 10:42:20">
irb(main):002:0> Factory.attributes_for(:code)
=> {:value=>"code"}

Any ideas?

Thanks,

like image 806
Robert Brown Avatar asked Feb 24 '11 10:02

Robert Brown


3 Answers

You can try something like this:

(Factory.build :code).attributes.symbolize_keys 

Check this: http://groups.google.com/group/factory_girl/browse_thread/thread/a95071d66d97987e)

like image 121
Claudio Acciaresi Avatar answered Nov 02 '22 22:11

Claudio Acciaresi


This one doesn't return timestamps etc., only attributes that are accessible for mass assignment:

(FactoryGirl.build :position).attributes.symbolize_keys.reject { |key, value| !Position.attr_accessible[:default].collect { |attribute| attribute.to_sym }.include?(key) }

Still, it's quite ugly. I think FactoryGirl should provide something like this out of the box.

I opened a request for this here.

like image 10
Joshua Muheim Avatar answered Nov 02 '22 23:11

Joshua Muheim


I'd suggest yet an other approach, which I think is clearer:

attr = attributes_for(:code).merge(code_type: create(:code_type))
like image 9
harm Avatar answered Nov 03 '22 00:11

harm