Monday, July 28, 2014

Testing with RSpec

Writing tests for your code is an investment into your own sanity in the future. Frequently, there are many more lines of test code than the actual code. I remember my surprise as I was going through Michael Hartl's Ruby on Rails Tutorial and realizing at some point I was learning more RSpec than Ruby or Rails. At least, it felt like that.

At the moment, my ratio of test code to actual code is still low, but I am getting there. It is also good to follow some best practices in describing tests, as it increases the readability of the code itself as well as the output.

Some good things to follow include using a period in describing a class method, and a pound sign in describing an instance method:

describe ".class_method" end; describe "#instance_method" end

Passing --format documentation as an argument creates a much more readable output results. Thus, running this block

describe Book do


    before :each do

        @book = Book.new "Title", "Author", :category

    end


    describe '#new' do

        it "returns a new book object" do

            @book.should be_an_instance_of Book

        end

    end


    describe "#title" do

        it "returns the correct title" do

            @book.title.should eql "Title"

        end

    end


    describe "#author" do

        it "returns the correct author" do

            @book.author.should eql "Author"

        end

    end


    describe "#category" do

        it "returns the correct category" do

            @book.category.should eql :category

        end

    end


end


returns results nicely formatted as follows:

Book

  #new

    returns a new book object

  #title

    returns the correct title

  #author

    returns the correct author

  #category

    returns the correct category


These things have been added to my arsenal.

No comments :

Post a Comment