-zsaow
Last Updated: February 25, 2016
·
325
· hauleth
Me

Easy creating nested read-only objects

When testing some objects that only read data from other class (like OAuth providers models or mailers) need to read objects that has very nested and complex structure (like OmniAuth hash). You could create OpenStruct but if you need to nest object then it isn't that easy. For my testing purposes I've created something like that:

class TestStruct < OpenStruct
  attr_accessor :raw_hash

  delegate :[], to: :raw_hash

  def initialize(hash)
    self.raw_hash = hash || {}
  end

  def method_missing(name, *args, &block)
    super unless raw_hash.key?(name)

    if raw_hash[name].is_a?(Hash)
      raw_hash[name] = TestStruct.new(raw_hash[name])
    else
      raw_hash[name]
    end
  end
end

It provide read-only structure that can be easily used through your tests as data provider.

Say Thanks
Respond