rspec - Rspec测试使用模拟和期望从范围限定的模型方法中进行有序检索

标签 rspec mocking rspec-rails stubbing

我是rspec, mock 和 stub 的新手。我逐渐开始欣赏并全面了解隔离测试和模拟/ stub 的概念。我有一个基本问题,我认为通过代码更容易解​​释:

class NewsItem < ActiveRecord::Base
  ...
  scope :ordered, order("created_at DESC")
  ...
end

现在,在我的模型测试中,我希望测试返回新闻列表的有序列表的行为。使用FactoryGirl DB-touching测试,我可以达到以下目的:
# TODO use mocking and stubbing here
it "should have an ordered method to retrieve news items in the descending order" do
  news_item_x = create(:news_item, created_at: DateTime.new(2012,01,01))
  news_item_y= create(:news_item, created_at: DateTime.new(2011,01,01))
  news_item_z= create(:news_item, created_at: DateTime.new(2012,03,01))

  # .all added to avoid comparison failure between groups of NewsItem objects an ActiveRel group.
  expect(NewsItem.ordered.all).to eql([news_item_z, news_item_x, news_item_y])
end 

我不知道要如何将上述测试转换为模拟和 stub 。这是第一次尝试,但显然我在这里误解了一些核心概念。
xit "should have an ordered method to retrieve news items in the descending order" do

  news_item_x = mock(NewsItem, created_at: DateTime.new(2012,01,01))
  news_item_y = mock(NewsItem, created_at: DateTime.new(2011,01,01))
  news_item_z = mock(NewsItem, created_at: DateTime.new(2012,03,01))

  NewsItem.should_receive(:ordered).and_return([news_item_z, news_item_x, news_item_y])
  # NewsItem.should_receive(:ordered).ordered # not working.

  # this is pointless as it's not checking the order of anything, just the call.
  NewsItem.ordered
end 

在这种测试中,模拟/ stub 甚至合适吗?

任何建议将不胜感激。

VERDICT:

@arieljuod和@zetetic都给了我很好的答案。对于我最初的问题,在这里进行 mock 和短句处理是否合适?正如@zetetic指出的,答案似乎是“否”。

另一方面,@ arieljuod提供了一种非常不错的方式来实际测试我的代码段(不一定通过模拟和 stub )。这两个都是有效的答案。

最佳答案

在这种测试中,模拟/ stub 甚至合适吗?

不。

使用模拟和 stub 的目的是将您编写的代码与依赖关系隔离开。在scope的情况下,它所依赖的一切都埋在了Rails框架中。同样,您不需要一开始就测试框架/库代码的内部结构-原始作者已经做到了。

关于rspec - Rspec测试使用模拟和期望从范围限定的模型方法中进行有序检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15140700/

相关文章:

c# - 如何制作 System.Net.Mail MailMessage 的模型?

Scala:模拟和蛋糕模式

ruby-on-rails - Rspec:如何使用局部变量和参数测试部分渲染?

ruby-on-rails - 如何在 RSpec View Examples 中设置语言环境

ruby-on-rails - 当我在 rails 的测试数据库中放置一条记录时,它会持续多长时间?

ruby-on-rails - cucumber 找不到步骤定义

ruby-on-rails - 如何对域或方法后的请求 stub ?

ruby - 如何测试单例类?

ScalaMock:如何模拟/ stub 方法以在每次调用时返回不同的值?

ruby-on-rails-4 - rails 4 - 找不到生成器 rspec :install