Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: How to assign instance variable in controller spec

class TestController < AplicationController   #....    private    def some_method     unless @my_variable.nil?       #...       return true     end   end end 

I want to test some_method directly in controller spec:

require 'spec_helper'  describe TestController do   it "test some_method"     phone = Phone.new(...)     controller.assign(:my_variable,phone) #does not work     controller.send(:some_method).should be_true   end end 

How I can set TestController instance variable @my_variable from controller spec?

like image 860
ole Avatar asked Apr 14 '13 22:04

ole


People also ask

How do I set an instance variable in RSpec?

If you want to set a controller or view's instance variables in your RSpec test, then call assign either in a before block or at the start of an example group. The first argument is the name of the instance variable while the second is the value you want to assign to it.

How do I mock an instance variable in RSpec?

You can't mock an instance variable. You can only mock methods. One option is to define a method inside OneClass that wraps the another_member , and mock that method. However, you don't have to, there is a better way to write and test your code.

What is assigns RSpec?

assigns relates to the instance variables created within a controller action (and assigned to the view).

What is describe in RSpec?

The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.


1 Answers

When testing private methods in controllers, rather than use send, I tend to use an anonymous controller due to not wanting to call the private method directly, but the interface to the private method (or, in the test below, effectively stubbing that interface). So, in your case, perhaps something like:

require 'spec_helper'  describe TestController do   controller do     def test_some_method       some_method     end   end    describe "a phone test with some_method" do      subject { controller.test_some_method }      context "when my_variable is not nil" do       before { controller.instance_variable_set(:@my_variable, Phone.new(...)) }       it { should be_true }     end      context "when my_variable is nil" do       before { controller.instance_variable_set(:@my_variable, nil) }        it { should_not be_true } # or should be_false or whatever     end        end end 

There's some good discussion on the issue of directly testing private methods in this StackOverflow Q&A, which swayed me towards using anonymous controllers, but your opinion may differ.

like image 163
Paul Fioravanti Avatar answered Sep 19 '22 14:09

Paul Fioravanti