开发者

How do I test for belongs_to and has_many in Rails?

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开发者_如何学Python find a good method online. So what should I use?


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


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) }


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜