Testing
Testing in Ruby is commonly done using a testing framework called RSpec
.
RSpec is a behavior-driven development (BDD) framework that allows you to write expressive and readable tests for your Ruby code.
Install RSpec
Add rspec
gem into your project's Gemfile and run:
bundle install
If you don't have a Gemfile, you can install it globally by running:
gem install rspec
Create a Spec File
In your project directory, create a spec
directory if it doesn't already exist. Inside the spec directory, create a file with a _spec.rb
extension. For example, if you have a calculator.rb
file, you can create a calculator_spec.rb
file in the spec directory.
Write the Tests
In your spec file, require the necessary files and start writing tests. RSpec uses a specific syntax that is designed to read like English sentences.
# spec/calculator_spec.rb
require_relative '../calculator'
describe Calculator do
describe '#add' do
it 'adds two numbers' do
calculator = Calculator.new
result = calculator.add(2, 3)
expect(result).to eq(5)
end
end
end
RSpec provides various matchers for making assertions in your tests. In the example above, expect(result).to eq(5)
is using the eq
matcher to check if the result
is equal to 5. There are many other matchers like be
, include
, match
, etc.
Run the Tests
Run the following command to execute your tests:
rspec
RSpec will discover and run all the spec files in your spec
directory and report the results.
Keep Going! Keep Learning!