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
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With