How to test puts in rspec

前端 未结 5 1138
遇见更好的自我
遇见更好的自我 2021-02-02 08:15

I want to do is run ruby sayhello.rb on the command line, then receive Hello from Rspec.

I\'ve got that with this:

class Hello
         


        
5条回答
  •  余生分开走
    2021-02-02 08:44

    I think the best way is to use rspec build in output matcher https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/output-matcher

    Fore example, this is your class

    class MakeIt
      def awesome(text)
        puts "Awesome #{text}"
      end
    end
    

    and your test

    describe MakeIt do
      describe '#awesome' do
        it 'prints awesome things' do
          expect do
            MakeIt.new.awesome('tests')
          end.to output('Awesome tests').to_stdout
        end
    
        it 'does not print not awesome things' do
          expect do
            MakeIt.new.awesome('tests')
          end.to_not output('Not awesome tests').to_stdout
        end
      end
    end
    

    Nice, clean and by the book!

提交回复
热议问题