これは、@antiqe と @Fitzsimmons の回答から最良のものを組み合わせた組み合わせアプローチです。ただし、かなり冗長です。
アイデアは、AR::Base.create のように動作するように Foo.create をモックすることです。最初に、ヘルパー クラスを定義します。
class Creator
def initialize(stub)
@stub = stub
end
def create(attributes={}, &blk)
attributes.each do |attr, value|
@stub.public_send("#{attr}=", value)
end
blk.call @stub if blk
@stub
end
end
そして、仕様でそれを使用できます。
it "sets the description" do
f = stub_model(Foo)
stub_const("Foo", Creator.new(f))
Something.method_to_test
f.description.should == "thing"
end
FactoryGirl.build_stubbed
の代わりに使用することもできますstub_model
。ただし、同じ問題が再び発生するためmock_model
、mock
またはを使用することはできません。double
これで、仕様は次のコード スニペットのいずれにも合格します。
Foo.create(description: "thing")
Foo.create do |foo|
foo.descrption = "thing"
end
foo = Foo.create
foo.descrption = "thing"
フィードバックをお待ちしております。