如何在Rails中测试belongs_to和has_many?

时间:2010-09-12 23:02:44

标签: ruby-on-rails ruby rspec

我正在使用rspec而我正在尝试测试我的模型y是否有很多x。我已经尝试了各种各样的东西,包括循环遍历方法数组,似乎无法在网上找到一个好的方法。那我该怎么用?

3 个答案:

答案 0 :(得分:19)

没有太多的黑客行为,你可以使用非凡的宝石:http://github.com/carlosbrando/remarkable

取自卓越的文档:

    describe Post do
      it { should belong_to(:user) }
      it { should have_many(:comments) }
      it { should have_and_belong_to_many(:tags) }
    end

答案 1 :(得分:7)

你可以反思课程:

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

如果您只使用Shoulda,可能会更容易,有辅助方法,所以它读得更干净:it { should have_many(:x) }

答案 2 :(得分:1)

这是一个独立于rspec的解决方案,关键是使用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