RSpec: how to set a controller's instance vari

2019-04-14 16:56发布

问题:

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 :)

回答1:

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. via assigns).

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.



回答2:

If set_inst_variable is a public method then simply call controller.set_inst_variable.

(It's usually preferrable to test through a class's public interface than alter its internal state).