DEV Community

Cover image for Tests Everywhere - Ruby
Roger Viñas Alcon
Roger Viñas Alcon

Posted on • Updated on

Tests Everywhere - Ruby

GitHub logo rogervinas / tests-everywhere

🤠 Tests, Tests Everywhere!

Ruby testing this simple Hello World with RSpec

Show me the code

Implementation

  1. Create HelloMessage class in HelloMessage.rb:
class HelloMessage
  def text
    @text = "Hello World!"
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Create HelloConsole class in HelloConsole.rb:
class HelloConsole
  def print(text)
    puts text
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Create HelloApp class in HelloApp.rb:
class HelloApp
  def initialize(message, console)
    @message = message
    @console = console
  end

  def printHello
    @console.print(@message.text)
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Create main function in Main.rb that wraps it all together:
message = HelloMessage.new
console = HelloConsole.new
app = HelloApp.new message, console
app.printHello
Enter fullscreen mode Exit fullscreen mode

Test

Following RSpec Core and RSpec Mocks guides ...

  1. Test HelloMessage in HelloMessage_spec.rb:
RSpec.describe HelloMessage do
  it "should return hello world" do
    message = HelloMessage.new
    expect(message.text).to eq("Hello World!")
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Test HelloApp in HelloApp_spec.rb:
RSpec.describe HelloApp do
  it "should print hello message" do
    messageText = "Hello Test!"

    # 2.1 Create a mock of HelloMessage
    # that will return "Hello Test!" whenever text is called
    message = instance_double("HelloMessage", :text => messageText)

    # 2.2 Create a mock of HelloConsole
    console = instance_double("HelloConsole")
    # 2.3 Expect print to be called once with "Hello Test!"
    expect(console).to receive(:print).once.with(messageText)

    # 2.4 Create a HelloApp, the one we want to test, passing the mocks
    app = HelloApp.new message, console
    # 2.5 Execute the method we want to test
    app.printHello

    # Expectation 2.3 will be checked once test ends
  end
end
Enter fullscreen mode Exit fullscreen mode
  1. Test output should look like:
HelloApp
  should print hello message

HelloMessage
  should return hello world

Finished in 0.00457 seconds (files took 0.05704 seconds to load)
2 examples, 0 failures
Enter fullscreen mode Exit fullscreen mode

Happy Testing! 💙

Top comments (0)