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
2010-09-12 23:25:38
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
2010-09-12 23:26:36
+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
2010-09-12 23:35:03
Very nice! I think I may start using that gem.
Mark Thomas
2010-09-13 01:13:24
Another option is Shoulda by thoughtbot, which has remarkably similar syntax. http://github.com/thoughtbot/shoulda
Beerlington
2010-09-13 02:00:06
Remarkable looks more complete than Shoulda. I haven't seen it before.
Andrew Vit
2010-09-13 02:28:37