How to check the return value of private methods in a controller
I want to test private methods (not action) of a controller using 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 =@controller.instance_eval{ some_action }
r.should eq 2
end
end
This is my code rspec
. However, it is r
always 1 and I have no idea how to pass the paramater to some_action
. How can I check valid return values some_methods
using rspec method? (eg r.should be_nil
)
link but doesn't work:
source to share
I am still a little confused. You don't have to care about the return value of the action controller . Actions should provide content, not return meaningful values. But I'll try to answer anyway.
If you are trying to make sure that you are FooController#some_action
calling a private method #some_methods
with a specific 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 almost never makes sense).
If you need to test behavior #some_methods
, you must write separate tests for this, using the techniques discussed in the articles you linked to.
source to share
It looks like you have several different problems here:
-
Why does r always return? r is always 1 because you are calling
some_action
from insance_eval.some_action
callssome_methods(true)
andsome_methods
returns 1 if passed true. With the code you providedsome_action
will always return 1 -
I assume these are just typos, but your class name
FooController
and controller is your testing in your rspecTestController
. In addition, the feature issome_methods
not marked as confidential. -
How to pass parameters , you should be able to call
some_methods
directly from the instance_eval block and pass as a normal function call:r = @controller.instance_eval{ some_methods(false) }
r.should eq 2
source to share