如何在Rails中测试belongs_to和has_many?

Bri*_*cks 8 ruby rspec ruby-on-rails

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

Tum*_*mas 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
Run Code Online (Sandbox Code Playgroud)

  • 另一种选择是thinkbot的Shoulda,它具有非常相似的语法.http://github.com/thoughtbot/shoulda (3认同)

And*_*Vit 7

你可以反思课程:

MyModel.reflect_on_association(:x).macro == :has_one
Run Code Online (Sandbox Code Playgroud)

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