views:

60

answers:

2

In one of my model's I'm using some meta programming to dynamically define some methods. I'd like to test this; thus, I need a compact way to assert my model has a readable/writable attribute with a certain name. Ideas?

I'm using shoulda for unit testing if it makes a difference.

+3  A: 

you might be able to use should_have_instance_methods or should_have_class_methods shoulda macros - I have not tried for this use case and they might rely on your object having super class of ActiveRecord::Base

what about respond_to?

o = some_dynamic_object()
assert(o.respond_to?(:method_x)) # getter
assert(o.respond_to?("method_x=".to_sym) # setter
house9
the should_have_xxx methods _do_ depend on subclassing from ActiveRecord::Base. But the respond_to part of your answer was very concise. Accepting.
TheDeeno
Shoulda (or test::unit, idk) has a convenience method: "assert_respond_to instance, sym"
TheDeeno
+2  A: 

There are several ways, depending on how it's defined. If you defined it normally (somehow def or define_method in an eval or class_eval), then you can use defined? obj.prop to ensure that it responds to a reader (there's no equivalent for a writer). You can also use obj.respond_to? :prop for the reader, and obj.respond_to? :prop= for the writer.

If you're using method_missing to mimic a call for the property, then obj.respond_to? will only work if you redefined that as well (in which case you need to test it separately), and the only way to test your property is to try reading from it and writing to it, and asserting that it doesn't throw any exceptions.

Ken Bloom
+1 for options.
TheDeeno