Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to mock/stub "puts" in Rails

I am printing some custom messages in my application using the puts command. However, I do not want these to be appearing in my Test Output. So, I tried a way to stub puts as shown below. But it still outputs my messages. What am I doing wrong ?

stubs(:puts).returns("") #Did not work out
Object.stubs(:puts).returns("") #Did not work out either
puts.stubs.returns "" #Not working as well
Kernel.stubs(:puts).returns "" #No luck

I am using Test::Unit

like image 201
bragboy Avatar asked Sep 14 '12 11:09

bragboy


People also ask

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

To be very clear and practical: 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 do you stub in Minitest?

Stubbing in Minitest is done by calling . stub on the object/class that you want to stub a method on, with three arguments: the method name, the return value of the stub and a block. The block is basically the scope of the stub, or in other words, the stub will work only in the provided block.

What is mock in Rails?

Mocks. Mocks are “smart” stubs, their purpose is to verify that some method was called. They are created with some expectations (expected method calls) and can then be verified to ensure those methods were called.

What is mock in RSpec?

What is a mock in RSpec? (Or a mock in general, because this isn't a concept unique to RSpec.) 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.


2 Answers

You probably need to stub it on the actual instance that calls puts. E.g. if you're calling puts in an instance method of a User class, try:

user = User.new
user.stubs(:puts)
user.some_method_that_calls_puts

This similarly applies to when you're trying to test puts in the top-level execution scope:

self.stubs(:puts)
like image 67
Kelvin Avatar answered Sep 27 '22 18:09

Kelvin


What I would do is define a custom log method (that essentially calls puts for now) which you can mock or silence in test quite easily.

This also gives you the option later to do more with it, like log to a file.

edit: Or if you really want to stub puts, and you are calling it inside an instance method for example, you can just stub puts on the instance of that class.

like image 30
Bitterzoet Avatar answered Sep 27 '22 19:09

Bitterzoet