Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a block is passed with RSpec Mocks

Tags:

ruby

rspec

rspec3

I can test if arguments are passed like:

RSpec.describe do
  it do
    obj = double
    expect(obj).to receive(:method).with(1, 2, 3)
    obj.method(1, 2, 3)
  end
end

How should I do about a block parameter? My ideal code:

RSpec.describe do
  it do
    obj = double
    proc = Proc.new{}
    expect(obj).to receive(:method).with(1, 2, 3).with_block(proc)
    obj.method(1, 2, 3, &proc)
  end
end
like image 438
sh01ch1 Avatar asked Dec 02 '14 07:12

sh01ch1


People also ask

How does a mock work in RSpec?

Mocking helps us by reducing the number of things we need to keep in our head at a given moment. Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.

What is stubbing in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

What is the difference between stubs and mocks in Ruby testing?

Stub: A class or object that implements the methods of the class/object to be faked and returns always what you want. Mock: The same of stub, but it adds some logic that "verifies" when a method is called so you can be sure some implementation is calling that method.

How does a mock work in Ruby?

A mock is an object used for testing.You use mocks to test the interaction between two objects. Instead of testing the output value, like in a regular expectation.


1 Answers

It seems that I cannot simply test if a block is passed with method chaining. And I found one dull answer, Block Implementation:

RSpec.describe do
  it do
    obj = double
    proc = Proc.new{}
    expect(obj).to receive(:method).with(1, 2, 3) do |*args, &block|
      expect(proc).to be(block)
    end
    obj.method(1, 2, 3, &proc)
  end
end

However, we cannot use a block implementation and other response configuration methods at the same time like receive(:method).with(1, 2, 3){|*| ...}.and_call_original.

like image 126
sh01ch1 Avatar answered Oct 22 '22 02:10

sh01ch1