Attributes_for Ruby 在 Rails 上与工厂女工进行了 4 次测试
Attributes_for Ruby on Rails 4 tests with factory girl
我正在尝试测试简单的 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),但它 returns 是一个完全没有关联的散列。期望中可能有一些有用的方法可以做到这一点?
我的工厂:
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
你可以单独创建属性然后合并它们,或者你可以用 FactoryGirl 试试 traits。
详情请看这两个SO问题:
- factory girl nested factory
我正在尝试测试简单的 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),但它 returns 是一个完全没有关联的散列。期望中可能有一些有用的方法可以做到这一点? 我的工厂:
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
你可以单独创建属性然后合并它们,或者你可以用 FactoryGirl 试试 traits。
详情请看这两个SO问题:
- factory girl nested factory