Rspec mocks: check expectations in it "should" methods?

I am trying to use rspec, mocking the setting of expectations that I can check in the "should" methods ... but I don’t know how to do this ... when I call the .should_receive methods on mock, it checks the expected call as soon as: all methods are completed.

here is a small example:

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

How can I check the expected call in the "he" method should? Do I need to use mocha or another mocking structure instead of rspec? or

+3
source share
5 answers

, , , . , , .

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

, , Bar.stub!(:new); , . @it.frob!(@bar). (, ), : def frob!(bar=Bar.new). , .

+8

, before. before , (it blocks). . :.

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"), .

+1

should_receive mock-, - . :

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

, BDD . , , . baz, , .

, should_receive , .

+1

, , - , , :

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

+1

, , , Bar ? , , . , ?

, , , .

0

Source: https://habr.com/ru/post/1720381/


All Articles