A step-by-step guide to setting up rspec in a pure Ruby project
Problem
A step-by-step guide to setting up rspec in a pure Ruby project
Situation
When it comes to testing Ruby applications, RSpec has emerged as a widely adopted testing framework, offering a powerful and expressive syntax.
While many tutorials focus on integrating RSpec with popular Ruby frameworks like Ruby on Rails, the process of using RSpec with pure Ruby often goes unnoticed.
In this comprehensive guide, we aim to bridge that gap by providing you with a step-by-step walkthrough on how to install and configure RSpec with pure Ruby.
Solution
Create project
Configure Gemfile
Configure rspec
Create a spec
Create a class
Create project
Create the directory's project
mkdir ruby-challenges
Configure Gemfile
Create the Gemfile
In the root of the app, create the Gemfile
by running the following command:
bundle init
The output should be something like this
Writing new Gemfile to /home/alexandre/var/www/ruby-challenges/Gemfile
Update Gemfile
Insert the following code into the Gemfile
:
# ruby-challenges/Gemfile
source "https://rubygems.org"
gem "rspec"
Install
This step is focused on installing rspec based on the content of the Gemfile
.
bundle install --path .bundle
Your output should look like this
Configure rspec
Create spec's directory
inside the project's directory ruby-challenges
mkdir spec
At the moment, this should be your project's structure: Run ls
ls
the output should look something like this
Gemfile spec
Create a spec
Create a spec file
# ruby-challenges/spec
touch string_checker_spec.rb
Initiate the spec implementation
# ruby-challenges/spec/string_checker_spec.rb
describe StringChecker do
end
Test
Let's test what we already have so far. In the root of the app:
# ruby-challenges/
bundle exec rspec
Your output would look something like the following picture
In this case, this error is totally normal and it indicates we don't have a StringChecker
class.
Require the model
This step consists in inserting the model file name into the rspec file.
# ruby-challenges/spec/string_checker_spec.rb
require "string_checker"
describe StringChecker do
end
My model name needs to be called string_checker.rb
Create a class
Create a lib directory
Insite the root of the application
mkdir lib
So far, this is the directory's structure:
Gemfile Gemfile.lock lib spec
Create the class
touch string_checker.rb
Implement the class
# ruby-challenges/lib/string_checker.rb:1
class StringChecker
end
Test it
bundle exec rspec
Your output should look something like this
No examples found.
Finished in 0.00007 seconds
0 examples, 0 failures
Repository
Check it out here.
Celebrate
There are no errors. Time to celebrate.
Let's get to know each other
Final thoughts
I hope this article helped you. Let me know if you have any questions.
Your thoughts, suggestions and corrections are more than welcome.
By the way, feel free to drop your suggestions on new blog articles.
Hope to see you next time.