I'm experimenting with RSpec.
Since I don't like mocks, I would like to emulate a console print using a StringIO
object.
So, I want to test that the Logger
class writes Welcome
to the console. To do so, my idea was to override the puts
method used inside Logger
from within the spec file, so that nothing actually changes when using Logger
elsewhere.
Here's some code:
describe Logger do
Logger.class_eval do
def puts(*args)
???.puts(*args)
end
end
it 'says "Welcome"' do
end
Doing this way, I need to share some StringIO
object (which would go where the question marks are now) between the Logger
class and the test class.
I found out that when I'm inside RSpec tests, self
is an instance of Class
. What I thought initially was to do something like this:
Class.class_eval do
attr_accessor :my_io
@my_io = StringIO.new
end
and then replace ???
with Class.my_io
.
When I do this, a thousand bells ring in my head telling me it's not a clean way to do this.
What can I do?
PS: I still don't get this:
a = StringIO.new
a.print('a')
a.string # => "a"
a.read # => "" ??? WHY???
a.readlines # => [] ???
Still: StringIO.new('hello').readlines # => ["hello"]