在rspec測試中填充實例變量

[英]Populating instance variables in rspec tests


I have a class which has the following initialise method.

我有一個類具有以下初始化方法。

def initialize(my_var)
  @my_var = my_var
end

and I want to test the method which then does something to @my_var

我想測試然后對@my_var做一些事情的方法

def split
  @my_var.split(",")
end

how do I change @my_var before testing that it returns an array properly?

在測試它是否正確返回數組之前如何更改@my_var?

Is this possible without having an accessor for @my_var?

如果沒有@my_var的訪問器,這可能嗎?

1 个解决方案

#1


25  

This doesn't sound like a correct practice. Rspec should be testing the interface behavior of your classes and models - not the internal implementation (of which instance variables undoubtedly are). There are ways to do this, but are you sure you don't want to have an accessor for that variable?

這聽起來不像是一種正確的做法。 Rspec應該測試類和模型的接口行為 - 而不是內部實現(毫無疑問是實例變量)。有辦法做到這一點,但你確定你不想擁有該變量的訪問者嗎?

Anyhow, you can use my_object.instance_variable_get("@my_var") and my_object.instance_variable_set("@my_var", value) to manipulate the variable.

無論如何,你可以使用my_object.instance_variable_get(“@ my_var”)和my_object.instance_variable_set(“@ my_var”,value)來操作變量。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/10/25/72f9888819c757e9ccdcab61a8a65bc0.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com