1

Is it possible to test a private method in controller? This essentially determines if the record should be saved in the database.

def create
    logger.debug "inside CREATE"
    @schedule = Schedule.new(params[:schedule])

    if is_valid_schedule # <-- this is the private method
        if @schedule.save
            flash[:success] = "New schedule entry added!"
            redirect_to @schedule
        else
            render 'new'
        end
    else
        flash.now[:error] = "Schedule has an overlap"
        render 'new'
    end
end

My tests look like this:

describe "POST #create" do

        let!(:other_schedule) { FactoryGirl.create(:schedule) }

        before(:each) { get :new }

        describe "with valid attributes" do
            it "saves the new schedule in the database" do


                expect{ post :create, schedule: other_schedule }.to change(Schedule, :count).by(1)

            end

            it "redirects to the :show template" do
                post :create, schedule: other_schedule
                response.should redirect_to other_schedule
                flash[:success].should eq("New schedule entry added!")
            end
        end
janejanejane
  • 496
  • 2
  • 12
  • 30

1 Answers1

3

During you create method test private method is_valid_schedule is called and tested. If you want to test this private method separately. Look at the example below:

class Admin::MembersController < Admin::BaseController
  #some code
  private
   def is_valid_example
     @member.new_record?
   end
end

And test for private method:

require 'spec_helper'
describe Admin::MembersController do
 .... 
 #some code
  describe "test private method" do
   it "should be valid" do
     member = FactoryGirl.create(:member)
     controller.instance_variable_set('@member', member)
     controller.send(:is_valid_example).should be(false)
   end
  end
end
Zh Kostev
  • 588
  • 3
  • 17