1

我正在将 rails 2 应用程序升级到 rails 3 并且不确定如何从我的一个测试中“升级”以下行

Category.should_receive(:find).with(:all,:conditions => {:parent_id => @parent_id}, :order => 'disp_order DESC').and_return(@categories_collection)

希望有人可以提供一些指示,因为我不是 100% 确定从哪里开始。

运行此程序时出现以下错误:

Failure/Error: Category.should_receive(:find).with(:all,
       (<Category(id: integer, permalink: string, name: string, parent_id: integer) (class)>).find(:all, {:conditions=>{:parent_id=>1}, :order=>"display_order DESC"})

* *更新 1

我现在看到一些非常奇怪的东西,我已经按照 Jim 的解释进行了重构(顺便说一句很好的解释!),但现在得到以下结果:

Failure/Error: Category.should_receive(:with_parent).with(1).and_return(@sub_category)
       (<Category(id: integer, permalink: string, name: string, parent_id: integer) (class)>).with_parent(1)
           expected: 1 time
           received: 0 times

但是,如果我将以下内容添加到我的测试中:

puts Category.with_parent(1).length.to_s

输出为“1” - 正确/预期值。由于某种原因,RSpec 没有看到这个并抛出错误。你知道为什么会发生这种情况吗?

* *更新 2

好的,有趣的是,如果我使用以下测试通过:

Category.with_parent(@parent_id).should == [@sub_category]

虽然这失败了:

Category.should_receive(:with_parent).with(@parent_id).and_return(@sub_category)

在 rspec2 的上下文中使用 should_receive & .ad_return 有问题吗?

4

1 回答 1

1

从您的测试行来看,被测代码似乎是:

Category.find(:all, :conditions => {:parent_id => @parent_id}, :order => 'disp_order DESC')

这种语法在 Rails 3 中被弃用,取而代之的是可链接的 AREL 调用,因此相同的 finder 函数现在可以写成:

Category.where(:parent_id => @parent_id).order('disp_order DESC')

您可能会说,由于方法链接,模拟这将变得更加困难。因此,最好的建议是将查找器重构为 Category 类上的一个方法(可能使用范围),该方法可以更容易地隔离和模拟。

例如:

class Category << ActiveRecord::Base

  scope :with_parent_id, lambda { |parent_id| where(:parent_id => parent_id).order('disp_order DESC') }

end

然后你可以像这样模拟 finder 调用:

Category.should_receive(:with_parent_id).with(@parent_id).and_return(@categories_collection)
于 2013-04-17T03:51:00.023 回答