私の理解から、工場の 'to_create'メソッドからの戻り値は無視されます。つまり、ファクトリの 'build'または 'initialize_with'部分から返されたオブジェクトは、テスト内で 'create'を呼び出すときに最終的に返されるオブジェクトです。FactoryGirl to_create戻り値
私の場合、私はリポジトリパターンのバリアントを使用しています。私はファクトリの 'to_create'部分をオーバーライドして、リポジトリ 'save'メソッドの呼び出しをインクルードします。このメソッドは、指定されたオブジェクトを変更するのではなく、保持されている元のフォームを表すオブジェクトを返します。
しかし、 'build'ブロックから返されたインスタンスは、 'to_create'ブロックで作成されたインスタンスではなく、ファクトリから返されます。私のコードでは、保存された属性から更新された属性(例えば、 'id')を持つオブジェクトではなく、オブジェクトの「固定されていない」形式が返されることを意味します。
'create'の戻り値を 'to_create'ブロックの結果またはそのブロック内で生成された値にする方法はありますか?
class Foo
attr_accessor :id, :name
...
end
class FooRepository
def self.create(name)
Foo.new(name) # this object is not yet persisted and has no .id
end
def self.save(foo)
# this method must not guarantee that the original Foo instance
# will always be returned
...
updated_foo # this is a duplicate of the original object
end
...
end
FactoryGirl.define do
factory :foo, class: FooRepository do
# create an example Foo
initialize_with { FooRepository.create(name: "Example") }
# save the Foo to the datastore, returning what may be a duplicate
to_create {|instance| FooRepository.save(instance)}
end
end
describe FooRepository do
it "saves the given Foo to the datastore" do
foo = create(:foo)
foo.id #=> nil
...
end
end
ニース!それはいくつかの異なる問題を助けましたが、非常に素晴らしい答えです:) – Aleks