如何设置方法测试中使用的私有实例变量? [英] How to set private instance variable used within a method test?

查看:22
本文介绍了如何设置方法测试中使用的私有实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个带有几个实例变量和一些方法的类.一些实例变量可通过attr_readerattr_accessor 设置访问.因此其他人是私人的.
一些私有实例变量在一个实例方法中设置并在另一个方法中读取/使用.

Given a class with a couple of instance variables and some methods. Some instance variables are set accessible via attr_reader and attr_accessor. Thus the others are private.
Some of the private instance variables get set within one of the instance methods and read/utilized within another method.

为了测试,我使用了 RSpec.由于我还是 Ruby 的新手并且想要把所有事情都做对,所以我将我的测试定义为相当细粒度的.因此,对于每个实例方法,我有一个 describe 块,它们本身被划分为 contexts 和 its 的子集.使用 before 定义一般环境前提条件.

For testing I'm using RSpec. As I'm still new to Ruby and want to get all things right, I defined my tests being rather fine-grained. Thus I've got one describe block for each instance method, which themselves are partitioned into a subset of contexts and its. General environmental preconditions are defined with before.

但是,在测试其中一种方法时,该方法正在使用但未设置其中一个私有变量,我需要调用另一种方法,该方法正在设置此变量.这对我来说似乎很重,而且不是模块化的.

However, when testing one of the methods, which is utilizing but not setting one of the private variables, I need to call the other method, which is setting this variable. This seems rather overweight and not modular for me.

有没有办法将私有实例变量强制为某个值.类似于使用Object::instance_eval(:var)删除"私有实例变量的值.

Is there a way of forcing a private instance variable to a certain value. Similar to "ripping out" the value of a private instance variable with Object::instance_eval(:var).

推荐答案

正如您在问题中回答的那样,设置实例变量的最简单方法是使用 instance_eval 方法:

As you answered in your question the easiest way to set instance variable is with instance_eval method:

obj.instance_eval('@a = 1')

另一种方法是使用 instance_variable_set:

Another way is to use instance_variable_set:

obj.instance_variable_set(:@a, 1)

但我不建议在您的规范中执行此操作.规范都是关于测试对象的行为,通过使用 instance_eval 破坏类封装来测试行为将使您的测试更加脆弱且依赖于实现.

But I would not recommend to do this in your specs. Specs are all about testing behavior of an object and testing behaviour by breaking class encapsulation with instance_eval will make your tests more fragile and implementation dependent.

对象状态隔离的替代方法是存根访问器方法:

Alternative approach to object state isolation is to stub accessor methods:

class UnderTest
  attr_accessor :a

  def test_this
    do_something if a == 1
  end
end

#in your test
under_test = UnderTest.new
under_test.stub(:a).and_return(1)

这篇关于如何设置方法测试中使用的私有实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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