KatPadi's Point

RSpec Adventures

RSpec is an awesome tool for behaviour-driven testing. It’s mostly used in test driven development (“TDD”), where the developer writes the test based on what the application should do, and then creates the program to accomplish the goals of the test.

At first, I found this tedious because it means extra work for me (the developer). But in the long run, it actually saves time in the process because I can easily tell whether the program is functioning properly.

There are many types of specs but for Rails to support functions, the specs need to have the corresponding metadata :type value:

  • Model specs: type: :model
  • Controller specs: type: :controller
  • Request specs: type: :request
  • Feature specs: type: :feature
  • View specs: type: :view
  • Helper specs: type: :helper
  • Mailer specs: type: :mailer
  • Routing specs: type: :routing

I haven’t tried doing Mailer and Routing specs but among the other types, Feature specs testing is my favorite because it simulates the application externally via the web pages. It’s like automating the user experience and it feels like magic because the web browser is moving on its own. Because of the “real user” interaction magic, feature specs require a special gem called Capybara.

Sample RSpec test file:

[pastacode lang=”ruby” path_id=”313c8951e3d39a27882c” highlight=”” lines=”” provider=”gist”/]

Sample Factory file:

[pastacode lang=”ruby” path_id=”87ba20bf2136072b3cc8″ highlight=”” lines=”” provider=”gist”/]

Another cool thing about this whole RSpec thingy is the Factory concept. Factories produce dummy data for tests. In my sample file, FactoryGirl is used. It basically just sets up test data but it creates Ruby objects as test data.

These are just basic tests that I can show but I’m sure I can do much more with it.

Although making tests requires additional time and effort, it’s a very good practice that will help devs maintain codes long-term. Plus, you won’t notice its “burden” because creating RSpec adventures are really enjoyable.

Leave a Reply

Your email address will not be published. Required fields are marked *