3

rspecのモックを使用して、「should」メソッドで検証できる期待値を設定しようとしています...しかし、これを行う方法がわかりません...モックで.should_receiveメソッドを呼び出すと、 before:allメソッドが終了するとすぐに、予期される呼び出しを検証します。

ここに小さな例があります:

describe Foo, "when doing something" do
 before :all do
  Bar.should_recieve(:baz)
  foo = Foo.new
  foo.create_a_Bar_and_call_baz
 end

 it "should call the bar method" do
  # ??? what do i do here?
 end
end

'it "should"'メソッドで予期される呼び出しを確認するにはどうすればよいですか?rspecの代わりにmochaまたは別のモックフレームワークを使用する必要がありますか?また ???

4

5 に答える 5

8

I'm going to take another whack at this, because it's clear from the initial set of answers and responses that there was some confusion about what you are trying to accomplish. Let me know if this is closer to what you are trying to do.

describe Foo, "when frobbed" do
  before :all do
    @it = Foo.new

    # Making @bar a null object tells it to ignore methods we haven't 
    # explicitly stubbed or set expectations on
    @bar = stub("A Bar").as_null_object
    Bar.stub!(:new).and_return(@bar)
  end

  after :each do
    @it.frob!
  end

  it "should zap a Bar" do
    @bar.should_receive(:zap!)
  end

  it "should also frotz the Bar" do
    @bar.should_receive(:frotz!)
  end
end

Incidentally, although it works I'm not a big fan of the Bar.stub!(:new) pattern; I usually prefer to pass collaborators in via optional arguments, e.g. @it.frob!(@bar). When not given an explicit argument (e.g. in the production code), the collaborator can be defaulted: def frob!(bar=Bar.new). This keeps the tests a little less bound to internal implementation.

于 2009-10-18T19:03:55.187 に答える
1

原則として、期待をbeforeブロックに入れてはいけません。 ブロックは、いくつかの例(ブロック)before間で共有される状態を設定するためのものです。it例自体に期待を入れてください。例えば:

describe Foo, "when doing something" do
  before :all do
   @foo = Foo.new
  end

  it "should call the bar method" do
    Bar.should_recieve(:baz)
    @foo.create_a_Bar_and_call_baz
  end
end

私は通常、アクションを説明するのではなく、describeブロックに特定の状態(たとえば)を説明させようとします。describe Car, "given a full tank of gas"

于 2009-10-18T01:56:06.113 に答える
1

私はこれが古い会話であることを知っていますが、誰かがまだ正しい答えを必要としている場合に備えて、ここに rpec モックスペクテーションを検証する方法の例を書きます:

require 'spec'
require 'spec/mocks'
include Spec::Mocks::ExampleMethods

o = mock('object')
o.should_receive(:respond_to?).once

space = Spec::Mocks::Space.new
space.add o

# here we should invoke methods, o.respond_to?:foo for instance

space.verify_all

乾杯

于 2010-05-15T19:17:12.147 に答える
1

should_receive メソッドは、メソッドが呼び出されたときに特定のものを返すようにモック オブジェクトをセットアップするために使用されます。次に例を示します。

Bar.should_recieve(:baz).with.({:arg1 => 'this is arg1', :arg2 => 'this is arg2'}).and_return(true)

通常、BDD では、アプリの動作をテストします。適切な動作を構築するためにどのメソッドが呼び出されたかをテストすることは重要ではありません。ある日、baz メソッドを削除することにした場合、アプリの動作が変わっていなくても、テストを更新する必要があります。

should_receive を意図しない方法で使用しようとしていると思います。

于 2009-10-18T14:35:04.917 に答える
0

単純に考えているのかもしれませんが、Bar とのやり取りを複数回検証する必要がありますか? もしそうなら、わかりませんが、わかりません。言い換えれば、文脈を混ぜていますか?

そうでない場合、それは観察の一部であるため、実際にはコンテキストではなく、自然に it ブロックに属します。

于 2009-10-18T04:03:45.350 に答える