使用 mocha 存根实例变量 [英] stub an instance variable using mocha

查看:25
本文介绍了使用 mocha 存根实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个直接引用实例变量的方法:

Let's say I have a method that references an instance variable directly:

class MyClass
  def method1
    puts @instance_var
  end
end

如何在 Test::Unit 测试中使用 mocha 存根 @instance_var 的值?

How can I stub out the value of @instance_var using mocha in a Test::Unit test?

推荐答案

虽然直接从单元测试访问对象的实例变量不是最佳实践,但如果您有充分的理由这样做,您可以使用instance_variable_set:

Although it is not considered a best practice to access an object's instance variables directly from a unit test, if you have a good reason for doing this, you can use instance_variable_set:

my_instance = MyClass.new
my_instance.instance_variable_set(:@instance_var, 'My updated value')

这篇关于使用 mocha 存根实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆