开发者

Ruby Testing: Testing for the Absence of a Method

In rspec and similar testing frameworks, how does one test for the absence of a method?

I've just started fiddling with rspec and bacon (a simplified version of 开发者_C百科rspec.) I wanted to define test that would confirm that a class only allows read access to an instance variable. So I want a class that looks like:

class Alpha
  attr_reader :readOnly

  #... some methods

end  

I am rather stumped:

  it "will provide read-only access to the readOnly variable" do
    # now what???
  end

I don't see how the various types of provided test can test for the absence of the accessor method. I'm a noob in ruby and ruby testing so I'm probably missing something simple.


In Ruby, you can check if an object responds to a method with obj.respond_to?(:method_name), so with rspec, you can use:

Alpha.new.should_not respond_to(:readOnly=)

Alternatively, since classes could override the respond_to? method, you can be stricter and make sure that there is no assignment method by actually calling it and asserting that it raises:

expect { Alpha.new.readOnly = 'foo' }.to raise_error(NoMethodError)

See RSpec Expectations for reference.


I believe you're looking for respond_to?, as in some_object.respond_to? :some_method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜