RSpec: how to set a controller's instance vari

2019-04-14 16:23发布

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

2条回答
我想做一个坏孩纸
2楼-- · 2019-04-14 16:43

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-04-14 16:50

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

查看更多
登录 后发表回答