相关疑难解决方法(0)

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

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

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)

有任何想法吗?

谢谢,

ruby-on-rails ruby-on-rails-3 factory-bot

31
推荐指数
3
解决办法
1万
查看次数

FactoryGirl:为什么attributes_for省略了一些属性?

我想在控制器测试中使用FactoryGirl.attributes_for,如:

it "raise error creating a new PremiseGroup for this user" do
  expect {
    post :create, {:premise_group => FactoryGirl.attributes_for(:premise_group)}
  }.to raise_error(CanCan::AccessDenied)
end
Run Code Online (Sandbox Code Playgroud)

...但这不起作用,因为#attributes_for省略了:user_id属性.这里的区别#create#attributes_for:

>> FactoryGirl.create(:premise_group)
=> #<PremiseGroup id: 3, name: "PremiseGroup_4", user_id: 6, is_visible: false, is_open: false)
>> FactoryGirl.attributes_for(:premise_group)
=> {:name=>"PremiseGroup_5", :is_visible=>false, :is_open=>false}
Run Code Online (Sandbox Code Playgroud)

请注意:不存在:user_id #attributes_for.这是预期的行为吗?

FWIW,我的工厂文件包含的定义:premise_group:user:

FactoryGirl.define do
  ...
  factory :premise_group do
    sequence(:name) {|n| "PremiseGroup_#{n}"}
    user
    is_visible false
    is_open false
  end
  factory :user do
    ...
  end
end
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails-3 factory-bot

16
推荐指数
1
解决办法
5346
查看次数