2

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 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.

madth3
  • 7,275
  • 12
  • 50
  • 74
TechZen
  • 64,370
  • 15
  • 118
  • 145
  • 3
    As a side note, Ruby is snake-cased by convention. Underscores separate words in method and variable names. – Matthew Ratzloff May 14 '11 at 03:00
  • Yes, I know but I'm working a lot in Objective-C with MacRuby so I tend to use camelCase out of habit. I'll try to remember not to do so in my post because I know how much not following conventions makes code hard to read. – TechZen May 14 '11 at 12:46

2 Answers2

5

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.

Jonathan Tran
  • 15,214
  • 9
  • 60
  • 67
  • 1
    This is probably the best way to do it, in classic duck typing fashion. For posterity, it's also possible to check for inclusion in the object's `methods` array: `Alpha.new.methods.include?(:readOnly=)` – Paul Rosania May 14 '11 at 04:13
  • Ah, yes, I was making this to hard. For some reason, I assumed that ruby lacked a "responds_to_ like function owing to duck typing. Most non-static typed languages have such a function and I should have known ruby would as well. – TechZen May 14 '11 at 12:49
2

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

Matthew Ratzloff
  • 4,518
  • 1
  • 31
  • 35