0

rspec 3.0.3 と ruby​​ 2.1.2 を使用していますが、何が問題なのかわかりません。コードの実装が適切でなくて申し訳ありません (つまり、クラス変数のことです)。

私は2つのクラスを持っています。最初に Test クラスの new_method を呼び出すと、@@c_var クラス変数を変更する AnotherTest.call_method を呼び出す必要があります。

require "rspec"

class Test
  def self.new_method
    AnotherTest.call_method
  end
end

class AnotherTest

  @@c_var = "hola"

  def self.call_method
     @@c_var = "holla from another test"
  end

  def self.c_var
    @@c_var
  end

end

そして、私はその仕様を書いています:

describe Test do
  it "should call method from an other class" do
    Test.new_method
    expect(AnotherTest.c_var).to be_eql("holla from another test")
  end
end

そして、この仕様は正常に動作しています。しかし、その後、「電話を受けることを期待する」を使用しようとしていますが、何か問題が発生します

describe Test do
  it "should call method from an other class" do
    expect(AnotherTest).to receive(:call_method).and_return("holla from another test")
    Test.new_method
    expect(AnotherTest.c_var).to be_eql("holla from another test")

  end
end

Failures:

1) Test should call method from an other class
 Failure/Error: expect(AnotherTest.c_var).to be_eql("holla from another test")
   expected `"hola".eql?("holla from another test")` to return true, got false
 # ./test.rb:26:in `block (2 levels) in <top (required)>'

RSpec は移行のようなものでこのチェックを行い、その後ロールバックを行っているようです。

とても奇妙なサンプルですが、私がこのバグに気付いたのは、クラスの 1 つのインスタンスのメソッドが別のインスタンスのメソッドを呼び出し、そのメソッドが何かを変更しようとしている場合だけです。

4

1 に答える 1

2

を使用することexpect(...).to receive(...)で、元のメソッドが呼び出されなくなります。むしろ、呼び出されると、and_return(...)メソッドを実際に実行せずに、渡したものを返すだけです。

おそらく欲しいのはand_call_original. このようにして、メソッドが呼び出されたことを確認しながら、実行を許可できます。

expect(AnotherTest).to receive(:call_method).and_call_original

ソース: https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs/configuring-responses/calling-the-original-implementation

于 2014-07-31T12:48:53.200 に答える