solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 229 forks source link

Testing my virtus objects #136

Closed changeclay closed 11 years ago

changeclay commented 11 years ago

I've created an RSpec matcher so I can just say something like this:

expect(described_class).to have_virtus_attribute(:administered_org_ids).
  of_type('Array[Integer]')

To make the comparison, it just makes a new attribute with these arguments, roughly as follows:

def is_a?(type_name) # e.g. is_a?('Array[Integer]')
  new_attribute_for_comparison(type_name) == attribute
end

def attribute
  model.attribute_set.find do |attribute|
    attribute.name == attribute_name
  end
end

def new_attribute_for_comparison(type_name)
  Virtus::Attribute.build(
    attribute_name,
    virtus_attribute_for_type(type_name),
    writer: :private
  )
end

def virtus_attribute_for_type(type_name)
  model.class_eval(type_name)
end

Could you suggest some ways to simplify this?

Thanks

solnic commented 11 years ago

You could tweak the matcher to accept something like:

expect(described_class).to have_virtus_attribute(:administered_org_ids).
  of_type(Array, :member_type => Integer)

then in the matcher you just do:

attribute = klass.attribute_set[:administered_org_ids]
attribute.options[:type] == Array && attribute.options[:member_type] == Integer
greyblake commented 11 years ago

@changeclay Probably virtus-rspec will be helpful for you.