[RSpec] How to Test Private Methods

Tadashi Shigeoka ·  Wed, January 23, 2013

Here’s a memo on how to test private methods in Ruby on Rails + RSpec.

If you create a private method called private_method in the User model as shown below:

■ app/models/user.rb

class User < ActiveRecord::Base
  def public_method
    "public"
  end
 
  private
    def private_method
      "private"
    end
end

In RSpec, you test the model by calling the private method using user.send(:private_method) as shown below:

■ spec/models/user_spec.rb

require 'spec_helper'

describe User do
  it 'public' do
    user = User.new
    user.public_method.should == "public"
  end
 
  it 'private' do
    user = User.new
    user.send(:private_method).should == "private"
  end
end

【Reference】

UKSTUDIO - Testing Private Methods with RSpec

That’s all from the Gemba.