美文网首页
rails测试mocha中的expects和stubs

rails测试mocha中的expects和stubs

作者: 夏_至 | 来源:发表于2015-11-06 14:50 被阅读197次

如果我们要写rails测试,那么mock可少不了。很多测试需要模拟一个特殊环境,比如需要当前时间是下午几点几点才能;或者需要访问一个外部api以获取某些特定数据。如果单纯为了测试而去改代码肯定是行不通的,那么我们就需要用到mock测试了。

mock测试就是在测试过程中,对于某些不容易构造或者 不容易获取的对象,用一个虚拟的对象来创建以便测试的测试方法。

mocha是rails测试中使用到的一个轻便的gem
https://github.com/freerange/mocha 按照文档,简单安装配置好就可以在测试里用上了。
一个简单的测试:

t = Time.parse('2015-10-11 14:00')
Time.expects(:now).returns(t)
assert_equal t , Time.now

而用stubs也同样可以

t = Time.parse('2015-10-11 14:00')
Time.stubs(:now).returns(t)
assert_equal t , Time.now

经过试验发现,如果expects指定的了方法,那么这次单元测试的过程中必须并且只用到一次这个方法
如果在第一块代码中间加一个puts Time.now 那么测试就会过不了,提示:
unsatisfied expectations:- expected exactly once, invoked twice: Time.now(any_parameters)
也就是说,而stubs则不会有这个问题,stubs一个方法,不管在后面的测试里有没有被用到,都不有问题
同时expects后面可以跟一些方法Time.expects(:now).returns(t).at_least_once表示期望now这个方法至少被调用一次……

看了下源代码,expects方法注释:

Adds an expectation that the specified method must be called exactly once with any parameters.
The original implementation of the method is replaced during the test and then restored at the end of the test. The temporary replacement method has the same visibility as the original method.

stubs:

Adds an expectation that the specified method may be called any number of times with any parameters.
The original implementation of the method is replaced during the test and then restored at the end of the test. The temporary replacement method has the same visibility as the original method.

原来只是一个检验调用次数,一个不校验 - -

还有个用法 User.any_instance.stubs(……).returns(……),原理一样,都是对mock方法的封装,也不用管mock和stub的区别了,很方便。
感觉rails写到后面就是找各种gem来用……哪个方便用哪个啊

相关文章

  • rails测试mocha中的expects和stubs

    如果我们要写rails测试,那么mock可少不了。很多测试需要模拟一个特殊环境,比如需要当前时间是下午几点几点才能...

  • rails 笔记(2)

    rails中的校验和测试 1、model 文件中增加validates,validates方法是个标准的Rails...

  • 【前端单元测试入门01】Mocha与chai

    Mocha 的简介 Mocha是流行的JavaScript测试框架之一,通过它添加和运行测试,从而保证代码质量 M...

  • JavaScript自动化测试介绍

    下面是对JavaScirpt自动化测试和持续集成内容的整理: 测试工具 mocha mocha是一种测试框架,是运...

  • 学习测试框架Mocha

    学习测试框架Mocha Mocha 是javascript测试框架之一,可以在浏览器和Node环境下使用,除了Mo...

  • 初识前端测试3 -- mocha

    mocha 在第一小结中的测试中用到了 mocha 框架,这一节就说说 mocha 框架吧。下面整理的内容主要来源...

  • 在rails中创建测试数据的几种方法

    一、创建测试数据 在rails中我们经常需要创建测试数据来测试功能有没有实现,除了在rails的console中创...

  • 第一周预习

    Mocha Mocha 是用于 Javascript 测试的框架。浏览器和 node 环境都可以使用。安装npm ...

  • Egg.js 单元测试入门

    官方推荐测试框架:Mocha(Mocha中文网) 官方推荐断言库:power-assert Egg.js 中已经内...

  • 4.vue造轮子-自动化测试

    使用 Karma + Mocha做单元测试使用 Karma + Mocha做单元测试使用 Karma + Moch...

网友评论

      本文标题:rails测试mocha中的expects和stubs

      本文链接:https://www.haomeiwen.com/subject/cjjchttx.html