4

このようなコードをrspecでテストするにはどうすればよいですか?

Foo.create! do |foo|
  foo.description = "thing"
end

オブジェクトが作成されたことをテストしたくない-適切なメソッドが適切なオブジェクトで呼び出されたかどうかをテストしたい。これをテストするのと同じです:

Foo.create!(description: "thing")

これとともに:

Foo.should_receive(:create!).with(description: "thing")
4

3 に答える 3

1

これはあなたが求めているものですか?

it "sets the description" do
  f = double
  Foo.should_receive(:create!).and_yield(f)
  f.should_receive(:description=).with("thing")

  Something.method_to_test
end
于 2012-11-01T20:28:42.190 に答える
0
Foo.count.should == 1
Foo.first.description.should == 'thing'
于 2012-11-01T07:03:10.843 に答える
0

これは、@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_modelmockまたはを使用することはできません。double

これで、仕様は次のコード スニペットのいずれにも合格します。

Foo.create(description: "thing")

Foo.create do |foo|
  foo.descrption = "thing"
end

foo = Foo.create
foo.descrption = "thing"

フィードバックをお待ちしております。

于 2012-11-20T16:17:38.167 に答える