Search code examples
ruby-on-railsrubyunit-testingmetaprogrammingshoulda

How do I assert that a model has a readable/writable attribute?


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.


Solution

  • 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