views:

112

answers:

3

I'm using rspec and I'm trying to test whether or not my model y has many x. I've tried all sorts of things, including looping through the methods array, and can't seem to find a good method online. So what should I use?

+1  A: 

You can reflect on the class:

MyModel.reflect_on_association(:x).macro == :has_one

It's probably easier if you just use Shoulda, there are helper methods so it reads much more cleanly: it { should have_many(:x) }

Andrew Vit
A: 

Hi,

here's an rspec independent solution, the key is to use reflect_on_assocation

class MyModel < ActiveRecord::Base
  has_many :children
  belongs_to :owner
end

reflection_children = MyModel.reflect_on_association(:children)

if !reflection_children.nil?
  if reflection_children.macro == :has_many
    # everything is alright
  else
    # it's not has_many but exists
  end
else
  # it doesn't exist at all !
end

reflection_owner  = MyModel.reflect_on_association(:owner)

if !reflection_owner.nil?
  if reflection_owner.macro == :belongs_to
    # everything is alright!
  else
    # it's not belongs_to but exists
  end
else
  # it doesn't exist at all!
end
sled
+4  A: 

Without much hacking you could use remarkable gem: http://github.com/carlosbrando/remarkable

Taken from remarkable docs:

    describe Post do
      it { should belong_to(:user) }
      it { should have_many(:comments) }
      it { should have_and_belong_to_many(:tags) }
    end
Tumas
Very nice! I think I may start using that gem.
Mark Thomas
Another option is Shoulda by thoughtbot, which has remarkably similar syntax. http://github.com/thoughtbot/shoulda
Beerlington
Remarkable looks more complete than Shoulda. I haven't seen it before.
Andrew Vit