RSpec Tips & Tricks - acanyon/RubyTuesdays-ConnectFour GitHub Wiki

RSpec is the unit testing framework that we're using. If you're new to programming/software development, early exposure to unit testing is wonderful.

Running tests

/HelloRubyTuesdays> rspec spec/                          # runs all the tests
/HelloRubyTuesdays> rspec spec/model/game_spec.rb        # runs just the tests for the Game model
/HelloRubyTuesdays> rspec spec/model/game_spec.rb:3      # runs the unit test in the Game spec that's at line 3

Basic test structure/methods

Here's one of the tests in spec/models/game_spec.rb.

  describe 'underlying relationships' do
    let(:empty_game) {FactoryGirl.create(:game)}

    it 'should be initialized with an empty board' do
      # create an empty board // array of 7 empty arrays
      empty_board = Array.new(7).map{[]}
      empty_game.board.should =~ empty_board
    end

    it 'should be initialized with status of :in_progress' do
      empty_game.status.should == 'in_progress'
    end
  end

Each it "....." do ... end block is a unit test (also called an example), which holds the assertions (all the should statements). The describe blocks serve as a way to organize and group the test class as a whole. Try running a test, and you'll see the organization at work.

Every test is based on some data that needs to be created before any assertions are made. In our example, let(:empty_game) {FactoryGirl.create(:game)} creates a local variable empty_game from FactoryGirl.

The assertions are designed to be read as close to English statements as possible - empty_game.status.should == 'in_progress' reads as "empty_game status should be equal to 'in_progress'."

Here's a tutorial that dives a little deeper into rspec. The various rspec doc pages are all linked to from http://rspec.info/, and if you're still stuck googling "rspec <method in question>" usually helps.

Stumbling blocks

If your controller test fails with this message:

ActionView::MissingTemplate: Missing template games/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :haml]}. Searched in:
  * "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0x007ff304011108>"

then the controller method it is trying to test is expected to have a redirect method in it. Take a look at the rails docs for some example redirects.