Write test and class code in the same file with autorun

Ruby on Rails / RSpec

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 a 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
  end

  def name
    [first_name, last_name].join(" ")
  end

  private
  attr_reader :first_name, :last_name
end

describe Person do
  describe "#name" do
    it "returns full name" do
      person = Person.new(first_name: "Tom", last_name: "Black")

      expect(person.name).to eq("Tom Black")
    end
  end
end

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.