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?
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.
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.
assigns relates to the instance variables created within a controller action (and assigned to the view).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With