如何检查类是否正确实例化

时间:2013-02-13 22:52:20

标签: ruby oop testing

说我有课:

class Product
  def initialize(v)
    @var = v
  end
end

我想用RSpec测试该类的实例化是否正常。它应该在班级或单元测试中进行测试,我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果您的初始化程序非常简单,那么测试它是不值得的。 另一方面,如果您在初始化程序中添加一些参数检查或其他逻辑,那么测试它可能是个好主意。

大多数情况下,在这种情况下的好习惯是在参数错误时引发IllegalArgumentError。在这种情况下,您可以确保初始化对象确实(或没有)引发错误。

如果你做了更复杂的事情,你可能想检查实例变量的值。我不认为使用attr_reader是一个好主意,因为我认为为测试目的更改类实现是一个坏主意。相反,我会使用#instance_variable_get来读取变量。

class Foo
  def initialize(mandatory_param, optional_param = nil)
    raise IllegalArgumentError.new("param cannot be #{param}") if mandatory_param == 42
    @var1 = mandatory_param
    @var2 = optional_param unless param.is_a? String
  end
end

describe Foo do
  it "should not accept 42 as an argument" do
    expect { Foo.new(42, 'hello') }.to raise_error(IllegalArgumentError)
  end

  it "should set var2 properly if it's not a String" do
    f = Foo.new('hello', 1)
    f.instance_variable_get(:@var2).should eq 1
  end

  it "should not set var2 if it's a String" do
    f = Foo.new('hello', 'world')
    f.instance_variable_get(:@var2).should be_nil
  end
end

答案 1 :(得分:0)

您需要在类中添加attr_reader,以便通过RSpec,Test :: Unit,Minitest或其他任何内容验证其状态。但是,你所说的基本上是测试Ruby作为一种语言正在运行,这真的不是你需要关注的事情。