如何在方法中存根类变量?

pro*_*int 3 rspec ruby-on-rails

需要帮助;)这是代码示例:

def some_method
  @some_variable = "some logic for a few strings and operations"
end
Run Code Online (Sandbox Code Playgroud)

我想像这样存根这个方法

controller.stub(:some_method).and_return( ??? )
Run Code Online (Sandbox Code Playgroud)

但 @some_variable 也应该被定义,我该怎么做?

Jag*_*ngh 6

你可以像这样存根它

allow(controller).to receive(:some_method) { your_return_value }
Run Code Online (Sandbox Code Playgroud)

只需使用上面的新语法进行存根即可。

对于你的实例变量,你可以这样做

controller.instance_variable_set(:@some_variable, value)
Run Code Online (Sandbox Code Playgroud)