Rails:使用RSpec测试命名范围

我是测试Rails Web应用程序和RSpec的新手。 我使用遗留代码并需要添加测试。 那么使用RSpec测试查找器和命名范围的最佳方法是什么?

我在Google中找到了一些方法,但它们并不理想。 例如:

http://paulsturgess.co.uk/articles/show/93-using-rspec-to-test-a-named_scope-in​​-ruby-on-rails

it "excludes users that are not active" do @user = Factory(:user, :active => false) User.active.should_not include(@user) end 

要么

http://h1labs.com/notebook/2008/8/21/testing-named-scope-with-rspec

 it "should have a published named scope that returns ..." do Post.published.proxy_options.should == {:conditions => {:published => true}} end 

我在“铁路测试处方”中找到最佳方法(恕我直言):

 should_match_find_method :active_only { :active == true } 

其中should_match_find_method自定义帮助方法

RSpec的创建者最近在博客中认为, validation是行为,协会是结构 。 换句话说,他发现不应该直接测试关联(和范围)。 对这些的测试将遵循您想要的行为。

换句话说,目前的智慧是没有必要直接测试每个范围,因为您将通过测试应用程序的行为来涵盖这些关联。

来自https://coderwall.com/p/hc8ofa/testing-rails-model-default_scope-with-rspec

  • 没有数据库查询
  • 无需在结构中表示查询

例:

 class Trip < ActiveRecord::Base default_scope { order(departure: :asc) } ... end RSpec.describe Trip, type: :model do it "applies a default scope to collections by departure ascending" do expect(Trip.all.to_sql).to eq Trip.all.order(departure: :asc).to_sql end end 

第一种方法的问题是它实际上是在查询数据库。 这是缓慢而不必要的。 如果您不介意,可以安全地使用第一种方法。 第二种方法快速而清晰,所以我会推荐它。