RSpec: how to set a controller's instance variable

ⅰ亾dé卋堺 提交于 2019-12-06 09:15:42

问题


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



来源:https://stackoverflow.com/questions/30579844/rspec-how-to-set-a-controllers-instance-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!