检查RSpec中的ActiveRecord关联

Alo*_*ain 17 testing bdd rspec ruby-on-rails

我正在学习如何使用Rspec编写测试用例.我有一个简单的帖子评论脚手架,其中一个帖子可以有很多评论.我正在使用Rspec进行测试.我应该怎么去检查Post :has_many :comments.我应该使用存根Post.comments方法,然后通过返回注释对象数组的模拟对象来检查它吗?真的需要测试AR协会吗?

Rob*_*her 28

由于ActiveRecord关联应该经过Rails测试套件(它们是)的良好测试,大多数人并不觉得有必要确保它们有效 - 它只是假设它们会.

如果你想确保你的模型正在使用那些关联,那就是不同的东西,而你想要测试它并没有错.我喜欢使用shoulda gem 来做到这一点.它可以让你做这样的事情:

describe Post do
  it { should have_many(:comments).dependent(:destroy) }
end
Run Code Online (Sandbox Code Playgroud)


mhr*_*ess 12

测试协会通常是一种良好的做法,特别是在TDD受到高度重视的环境中 - 其他开发人员在查看相应的代码之前通常会查看您的规范.测试关联可确保您的spec文件最准确地反映您的代码.

您可以通过两种方式测试关联:

  1. 使用FactoryGirl:

    expect { FactoryGirl.create(:post).comments }.to_not raise_error
    
    Run Code Online (Sandbox Code Playgroud)

    这是一个相对肤浅的测试,将与工厂一样:

    factory :post do
      title { "Top 10 Reasons why Antelope are Nosy Creatures" }
    end
    
    Run Code Online (Sandbox Code Playgroud)

    如果您的模型缺少has_many与注释的关联,则返回NoMethodError .

  2. 您可以使用ActiveRecord #reflect_on_association方法更深入地了解您的关联.例如,通过更复杂的关联:

    class Post
      has_many :comments, through: :user_comments, source: :commentary
    end
    
    Run Code Online (Sandbox Code Playgroud)

    您可以深入了解您的关联:

    reflection = Post.reflect_on_association(:comment)
    reflection.macro.should eq :has_many
    reflection.options[:through].should eq :user_comments
    reflection.options[:source].should eq :commentary
    
    Run Code Online (Sandbox Code Playgroud)

    并测试相关的任何选项或条件.