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

I print some custom messages in my application using the puts command. However, I do not want them to appear in my test release. So, I tried a way to puts , as shown below. But he still displays 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

+4
source share
4 answers

You probably need to stub it in the actual instance that puts calls. For instance. if you call puts in the instance method of the User class, try:

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

Similarly, if you are trying to test puts in the top-level execution area:

 self.stubs(:puts) 
+4
source

What I would like to do is define my own logging method (which essentially calls puts for now), which you can easily ridicule or silence in the test.

It also gives you the opportunity to do more with it later, for example, write to a file.

edit: If you really want to stub puts, and you call it inside the instance method, for example, you can just stub puts on the instance of this class.

+1
source

So, comments on the original post indicate the answer:

 Kernel.send(:define_method, :puts) { |*args| "" } 

Instead of drowning out all the output, I would just disconnect the output from the specific objects that are placed during your tests.

 class TestClass def some_method ... puts "something" end end it "should do something expected" do TestClass.send(:define_method, :puts) { |*args| "" } test_class.some_method.should == "abc123" end 
0
source

Using Rails 5 + Mocha: $stdout.stubs(puts: '')

0
source

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


All Articles