RSpec:如何设置控制器的实例变量 [英] RSpec: how to set a controller's instance variable
问题描述
我的rails控制器中有以下方法:
I have a this method in my rails controller:
def some_init_func
# ...
@inst_var = 1
# ...
end
:
do_something_with(@inst_var)
如何在RSpec中设置此实例变量?
How do I set this instance variable in RSpec?
allow(controller).to receive(:some_init_func) do
# ???? what goes here ????
end
推荐答案
Assign
是可用于视图测试的RSpec方法,但控制器测试不支持该方法。通常希望控制器 set 设置实例变量,因此RSpec不允许设置它们,但是允许检查它们(即通过 assigns
)。
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
).
不过,为了回答您的问题,Ruby在所有对象上都提供了 instance_variable_set
方法,您可以从您的控制器测试调用如下:
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)
请参见 http ://ruby-doc.org/core-2.2.2/Object.html#method-i-instance_variable_set 以获取文档,并注意用舌头示意。
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.
这篇关于RSpec:如何设置控制器的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!