[Ruby] (´-`)..oO (I want to find the standard output “Hello” easily.

1 minute read

I am a Ruby newbie.

Today I created a rake task that just outputs “Hello World”.

# rake hoge:hello
"Hello World"

I’d like to write a test to check that the result contains “Hello” and I’d like to find a way to find it simply by specifying a string. .. ..

code

hoge_spec.rb


require'rails_helper'
require'rake'

RSpec.describe'Hoge', type: :task do

  #Omitted

  describe'rake hoge:hello' do
    let(:task) {'hoge:hello'}

    context'Find Hello on standard output' do

      it'It is a standard output and the character string to the argument of Hello #1 output matcher' do
    # * Ideal type. However, it does not match exactly, so it fails. .. ..
        expect{ @rake[task].invoke() }.to output('Hello').to_stdout
      end

      it'regular expression in standard output as argument of Hello #2 output matcher' do
    # It works, but it's difficult to use regular expression matching. .. ..
        expect{ @rake[task].invoke() }.to output(/Hello/).to_stdout
      end

      it'partial match with Hello #3 include on standard output' do
    # It works, but the code is long. .. ..
        $stdout = StringIO.new
        @rake[task].invoke()
        output_text = $stdout.string
        $stdout = STDOUT
        expect(output_text).to include'Hello'
      end
    end
  end

end

Execution result

image.png

image.png

…I thought it would be nice if I could do it by specifying the character string (#1), but this is an error. The only way to realize the purpose is to use regular expressions (# 2) or assign standard output to variables (# 3). .. .. I’m wondering if there is any good way.