I have a this method in my rails controller:
def some_init_func
# ...
@inst_var = 1
# ...
end
and later on:
do_something_with(@inst_var)
How do I set this instance variable in RSpec?
allow(controller).to receive(:some_init_func) do
# ???? what goes here ????
end
Muchas gracias :)
assign
is an RSpec method available for view tests, but it's not supported for controller tests. Controllers are typically expected to set instance variables, so RSpec doesn't allow for setting them, but it does allow for checking them (i.e. viaassigns
).To answer your question, though, Ruby has a
instance_variable_set
method available on all objects, which you can invoke from your controller test as follows:controller.instance_variable_set(:@inst_var, 1)
See http://ruby-doc.org/core-2.2.2/Object.html#method-i-instance_variable_set for documentation, and note the tongue-in-cheek explanation.
If
set_inst_variable
is a public method then simply callcontroller.set_inst_variable
.(It's usually preferrable to test through a class's public interface than alter its internal state).