【问题标题】:Attributes_for Ruby on Rails 4 tests with factory girlAttributes_for Ruby on Rails 4 与工厂女孩的测试
【发布时间】:2015-11-23 17:58:05
【问题描述】:

我正在尝试测试简单的 POST 控制器#create 方法。

it "saves the new object in the DB" do
  object = build(:object_with_association)
  expect { post :create, object: object.attributes }.to change(SomeObject, :count).by(1)
end

object.attributes 是不是最好的方法?我尝试使用 attributes_for(:object_with_association),但它返回一个没有关联的哈希。可能有一些有用的方法可以在期望中做到这一点? 我的工厂:

factory :obj do
  name "A"
  association :first, factory: :first
  association :second, factory: :second

  factory :obj_with_association do
    transient do
      nested_count 5
    end

    after(:build) do |obj, evaluator|
      create_list(:nested, evaluator.nested_count, obj: obj)
    end
  end
end

:first 和 :second 的关联是 belongs_to,:nested 的关联是 has_many

【问题讨论】:

    标签: ruby-on-rails ruby rspec factory-bot


    【解决方案1】:

    您可以单独创建属性并合并它们,也可以尝试使用 FactoryGirl 的特征。

    详情请看这两个 SO 问题:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      相关资源
      最近更新 更多