Paluy on Miscellaneous

Of course I'm an optimist - I don't see much point in being anything else. - Winston Churchill

RSpec - Less Known Features

I would like to summarize some of less known RSpec feature I use during my development.

Execute specific test from command line

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# spec/controllers/user_controller_spec.rb
require 'spec_helper'

describe UsersController do

  before (:each) do
    @user = FactoryGirl.create(:user)
    sign_in @user
  end

  describe "GET 'show'" do

    it "should be successful" do
      get :show, id: @user.id
      response.should be_success
    end

    it "should find the right user" do
      get :show, id: @user.id
      assigns(:user).should == @user
    end

  end

end

Suppose you want to test only the test at line #17. You can append the line number to file pathrun:

1
rspec spec/controllers/user_controller_spec.rb:17

It will run only the test inside the scoped line. The same can be used with describe/context.

Temporary pending test

Suppose you need temporary disable a test at line #8. You can add x before it and the test is pending now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
describe "GET 'show'" do

  it "should be successful" do
    get :show, id: @user.id
    response.should be_success
  end

  # THIS TEST IS PENDING NOW
  xit "should find the right user" do
    get :show, id: @user.id
    assigns(:user).should == @user
  end

end

Focus on specific test

Add a tag to the selected test:

1
2
3
4
5
6
7
8
9
10
11
12
13
describe "GET 'show'" do

  it "should be successful", focus: true do
    get :show, id: @user.id
    response.should be_success
  end

  it "should find the right user" do
    get :show, id: @user.id
    assigns(:user).should == @user
  end

end

Then, run rspec as following: rspec -t focus

Rails.logger stub

If you need to stub Rails logger, you should do the following:

1
2
3
4
5
6
7
8
9
10
# Expecting to receive Rails.logger.debug some_message
let(:logger_mock) { double("Rails.logger").as_null_object }
Rails.stub_chain(:logger, :debug).and_return(logger_mock)

# your test goes here
# ...
#

# Don't forget to unstub the logger at the end of test!
Rails.unstub(:logger)

More about stub_chain

Comments