我如何对我的默认范围进行 rspec 测试 [英] How can i have rspec test for my default scope

查看:10
本文介绍了我如何对我的默认范围进行 rspec 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型有 default_scope(:order => 'created_at' )我的测试(rspec、工厂女孩、shouda 等)是:

my model has default_scope(:order => 'created_at' ) my tests (rspec, factory girl, shoulda, etc.) are:

require 'spec/spec_helper.rb'

describe CatMembership do
  context "is valid" do
    subject { Factory.build(:cat_membership) }
    it { should be_valid }
    it { should belong_to :cat}
    it { should belong_to :cat_group}
    it { should have_db_column(:start_date)}
    it { should have_db_column(:end_date)}
  end
end

推荐答案

我宁愿使用查询来测试并检查结果,但如果你真的必须这样做,Rails 3 的一个可能的解决方案是这样的:

I would rather have this tested using a query and checking the results, but if you really must do it, one possible solution would be something like this for Rails 3:

CatMembership.scoped.to_sql.should == CatMembership.order(:created_at).to_sql

在 Rails 2 上:

And on Rails 2:

CatMembership.default_scoping.should == [{:create=>{}, :find=>{:order=>"created_at"}}]

但我不会说这些解决方案是理想的,因为它们展示了大量的实现知识(您可以看到实现随不同的 Rails 版本而变化).

But I would not say these solutions are ideal since they show a lot of knowledge of the implementation (and you can see the implementation varies with different Rails versions).

创建示例数据、运行通常的all 查询并检查结果是否正确排序可能更简单,更接近于真正的单元测试,并且即使在升级 Rails 版本时也能正常工作.

Creating sample data, running an usual all query and checking the result is correctly ordered might have been simpler, would be closer to real unit testing and would work even as you upgrade your rails version.

在这种情况下可能是:

before do
  @memberships = []

  @memberships << CatMembership.create!
  @memberships << CatMembership.create!
  @memberships << CatMembership.create!

  [ 1.hour.ago, 5.minutes.ago, 1.minute.ago ].each_with_index do |time, index|
    membership = @memberships[index]
    membership.created_at = time
    membership.save
  end

end

it 'should be correctly ordered' do
  @sorted_memberships = CatMembership.all
  @memberships.first.should == @sorted_memberships.last
  @memberships.second.should == @sorted_memberships.second
  @memberships.third.should == @sorted_memberships.first
end

它更加冗长,但即使您在轨道上前进,它也会起作用.

It's much more verbose, but it's going to work even as you move forward on rails.

现在我才注意到是谁提出了这个问题:D

And now I have just noticed who asked the question :D

这篇关于我如何对我的默认范围进行 rspec 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆