FactoryGirl:attributes_for没有给我相关的属性

Rob*_*own 31 ruby-on-rails ruby-on-rails-3 factory-bot

我有一个像这样的代码模型工厂:

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

但是,当我用一个简单的test_should_create_code测试我的控制器时,如下所示:

  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
Run Code Online (Sandbox Code Playgroud)

......测试失败了.未创建新记录.

在控制台中,似乎attributes_for不会返回所有必需的属性,如create.

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"}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

谢谢,

Cla*_*esi 23

你可以尝试这样的事情:

(Factory.build :code).attributes.symbolize_keys 
Run Code Online (Sandbox Code Playgroud)

请检查:http://groups.google.com/group/factory_girl/browse_thread/thread/a95071d66d97987e)

  • 这有返回时间戳,id等不必要的副作用......对所有问题都不是真正的解决方案 (7认同)
  • @coneybeare:有一个简单的解决方法.请参阅http://stackoverflow.com/questions/10290286/factory-why-does-attributes-for-omit-some-attributes上的解决方案 (2认同)

Jos*_*eim 10

这个不返回时间戳等,只返回可用于批量分配的属性:

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

不过,这很难看.我认为FactoryGirl应该提供开箱即用的东西.

在这里开了一个请求.


har*_*arm 9

我建议另一种方法,我认为更清楚:

attr = attributes_for(:code).merge(code_type: create(:code_type))
Run Code Online (Sandbox Code Playgroud)

  • 你也可以做`attributes_for(:code).merge(code_type_attributes:attributes_for(:code_type))` (2认同)