Ruby测试:测试缺少方法

Tec*_*Zen 2 ruby unit-testing rspec macruby

在rspec和类似的测试框架中,如何测试缺少方法?

我刚刚开始摆弄rspec和培根(rspec的简化版本.)我想定义测试,确认一个类只允许对实例变量的读访问.所以我想要一个看起来像这样的课程:

class Alpha
  attr_reader :readOnly

  #... some methods

end  
Run Code Online (Sandbox Code Playgroud)

我很难过:

  it "will provide read-only access to the readOnly variable" do
    # now what???
  end
Run Code Online (Sandbox Code Playgroud)

我没有看到各种类型的提供的测试如何测试缺少访问器方法.我是红宝石和红宝石测试中的菜鸟,所以我可能会错过一些简单的东西.

Jon*_*ran 5

在Ruby中,您可以检查对象是否响应方法obj.respond_to?(:method_name),因此使用rspec,您可以使用:

Alpha.new.should_not respond_to(:readOnly=)
Run Code Online (Sandbox Code Playgroud)

或者,由于类可以覆盖该respond_to?方法,因此您可以更严格并确保通过实际调用它并声明它引发的方法没有赋值方法:

expect { Alpha.new.readOnly = 'foo' }.to raise_error(NoMethodError)
Run Code Online (Sandbox Code Playgroud)

请参阅RSpec Expectations以供参考.