hey mike
hey mike

Reputation: 2471

How to check return value of private methods in controller

I want to testing a private methods(not a action) of controller with rspec

class FooController < ApplicationController
  def some_methods( var )
    if  var 
      return 1
    else 
      return 2
    end
  end

  def some_action
    var = true
    r = some_methods(var)
    r
  end
end

rspec:

require 'spec_helper'

describe FooController do
   describe "GET index" do
      it "get get return value from some_methods" do
          @controller = TestController.new
          r [email protected]_eval{ some_action }  
          r.should eq 2
  end
end

This is my rspec code. However, the r is always 1 and I don't know how to pass paramater into some_action. How can I validate the real return values of some_methods using rspec way ? ( ex: r.should be_nil )

referenced but not work:

  1. Rspec, Rails: how to test private methods of controllers?

  2. How to spec a private method

Upvotes: 3

Views: 3932

Answers (3)

Brandan
Brandan

Reputation: 14983

I'm still a little confused. You shouldn't care about the return value of a controller action. Actions are supposed to render content, not return meaningful values. But I'll try to answer anyway.

If you're trying to make sure that FooController#some_action calls the private method #some_methods with a certain parameter, you can use #should_receive:

describe FooController do
  describe 'GET index' do
    it 'should get the return value from some_methods' do
      controller.should_receive(:some_methods).with(true).and_return(1)
      get :index
    end
  end
end

This example will fail if the controller never receives the message :some_methods, but it doesn't actually check the return value of the method #some_action (because that's almost never meaningful).

If you need to test the behavior of #some_methods, you should write separate tests for that using the techniques discussed in the articles you referenced.

Upvotes: 4

plainjimbo
plainjimbo

Reputation: 7100

It looks like you've got a few different issues going on here:

  1. Why is r always returning 1? r is always 1 because you're calling some_action from insance_eval. some_action calls some_methods(true), and some_methods returns 1 if true is passed in. With the code you've supplied, some_action will always return 1

  2. I'm guessing these are just typo's, but your class name is FooController and the controller your testing in your rspec is TestController. Also, the some_methods function isn't marked as private.

  3. How to pass parameters, you should be able to call some_methods directly from your instance_eval block and pass in a parameter like a normal function call:

    r = @controller.instance_eval{ some_methods(false) }

    r.should eq 2

Upvotes: 2

Vik
Vik

Reputation: 5961

Check into log with print/puts statement or use debugger 'rails-debug' to check value at run-time .

puts r = some_methods(var)

Upvotes: 0

Related Questions