dev-resources.site
for different kinds of informations.
Tests Everywhere - Ruby
Published at
11/23/2023
Categories
test
ruby
rspec
tutorial
Author
Roger Viñas Alcon
rogervinas / tests-everywhere
🤠 Tests, Tests Everywhere!
Ruby testing this simple Hello World with RSpec
-
Show me the code
- Implementation
- Test
- Run this project using 🐳 docker
- Run this project locally
Show me the code
Implementation
- Create
HelloMessage
class in HelloMessage.rb:
class HelloMessage
def text
@text = "Hello World!"
end
end
- Create
HelloConsole
class in HelloConsole.rb:
class HelloConsole
def print(text)
puts text
end
end
- 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
- Create main function in Main.rb that wraps it all together:
message = HelloMessage.new
console = HelloConsole.new
app = HelloApp.new message, console
app.printHello
Test
Following RSpec Core and RSpec Mocks guides ...
- 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
- 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
- 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
Happy Testing! 💙
Articles
12 articles in total
Tests Everywhere - Swift
read article
Tests Everywhere - COBOL
read article
Tests Everywhere - Scala
read article
Tests Everywhere - Rust
read article
Tests Everywhere - Ruby
currently reading
Tests Everywhere - Python
read article
Tests Everywhere - Kotlin
read article
Tests Everywhere - JavaScript
read article
Tests Everywhere - Java
read article
Tests Everywhere - Go
read article
Tests Everywhere - .NET C#
read article
Tests Everywhere - Bash
read article
Featured ones: