redirect to stderr

6 views
Skip to first unread message

Joao Miguel Ferreira

unread,
Dec 11, 2021, 1:50:30 PM12/11/21
to rs...@googlegroups.com
Hello all,

Is there a way to remove from the output all the "puts" and "ap" text lines printed by the code being tested or even printed by the spec code itself ?

Ideally it would be possible to only see spec context and describe lines and all other things would be redirected somewhere else. stderr is a good option since it would allow the tester to capture all that into a text file as evidences for alter inspection

Would be very nice for me if such an option exists.

Cheers, thank you
Joao

Jon Rowe

unread,
Dec 12, 2021, 5:39:37 AM12/12/21
to rs...@googlegroups.com
Hello

RSpec tries not to monkey patch standard Ruby methods, so `puts` etc will always try to output to `$stdout`, we do provide a matcher which redirects `$stdout` and/or `$stderr` to a `StringIO` temporarily, which can be used as:

```
expect { code }.to output.to_stdout # and/or `to_stderr`
```

But thats temporary and has a few limitations (we don't overwrite `STDOUT` / `STDERR` and if code has captured the globals we obviously can't change those references.

If you wanted to do this yourself throughout the spec run its very easy to do in Ruby, for example to redirect stdout to stderr during the run of a test you could do:

```
RSpec.configure do |config|
  config.around(:example) do |example|
    original_stdout = $stdout
    $stdout = $stderr
    example.call
    $stdout = original_stdout
  end
end
```

Note it would be important to set stdout back to get the normal output during the spec run.

Hope that helps achieve what you want.

Cheers
Jon
--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.

Phil Pirozhkov

unread,
Dec 12, 2021, 7:12:56 AM12/12/21
to Jack Royal-Gordon
If you stick to a convention that you output debug messages to stderr and pipeable program output goes to stdout, it will be easier to separate the two.
For better or worse, RSpec outputs to stdout.

Reply all
Reply to author
Forward
0 new messages