Ruby on Rails testing

Rails / RSpec – write test and class code in the same file with autorun

Rails / RSpec – write test and class code in the same file with autorun February 23, 2018Leave a comment

I think I already convinced you that you should write tests for your application. We went through different types of stubs such as spies, stubs and mocks but this time I want to move on some more general subject.

In most cases, you have your tests separated from your code which is natural but there is sometimes need to write tests and testing code in the same class – for teaching or demonstrating purposes. And here comes RSpec autorun feature with help. If you have rspec gem already installed you can just create new file, let’s name it test.rb and then require rspec/autorun at the top of it and you can enjoy writing test and code in the same file.

require 'rspec/autorun'

class Person
  def initialize(first_name:, last_name:)
    @first_name = first_name
    @last_name = last_name
  def name
    [first_name, last_name].join(" ")
  attr_reader :first_name, :last_name

describe Person do
  describe "#name" do
    it "returns full name" do
      person = "Tom", last_name: "Black")
      expect( eq("Tom Black")

And then you can run ruby test.rb and check the result. That kind of testing is very useful if you are learning TDD and you want to practice some basic stuff.

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

Leave a Reply

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