---
title: "Rails 3 中使用jasmine 测试Javascript"
author: "iseesea"
date: "2011-01-21T13:43:44Z"
tags: ["Android", "JavaScript", "Rails", "Ruby", "rspec"]
categories: ["编程语言"]
slug: "rails-3-jasmine-javascript"
draft: false
lastmod: "2011-01-21T13:48:09Z"
id: 890811
url: "https://iseesea.iteye.com/blog/890811"
---

虽然测试js代码很恶心；但是要测试，特别是写很多js的时候； 在一个项目中，使用jasmine来测试我们一个需要很多很多js代码的页面；对于那个页面，我都觉得都已经写了一个Js的UI了。。。。当初没有用现成的JS UI框架，真是失误啊～ Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests. 这是jasmine的介绍； 项目链接：http://pivotal.github.com/jasmine/index.html 测试代码结构是： \[code="javascript"] describe("Jasmine", function() { it("makes testing JavaScript awesome!", function() { expect(yourCode).toBeLotsBetter(); }); }); \[/code] 很有rspec的风格；开始用它（Rails3）； 第一步： 把 gem "jasmine" 添加到项目的特定环境组里； 然后运行 \[code="ruby"] $ bundle install $ bundle exec jasmine init \[/code] 上面第二行是初始化 jasmine，他会在项目目录底下产生一些测试例子，供我们参考： 在 public/javascripts/中产生 player和song的js文件。 在spec/中产生 javascripts 文件夹，里面有一些测试例子； 我们写的测试代码就是放在这个文件夹底下； 第二步： 运行 \[code="ruby"]rake jasmine\[/code] 然后点击打开http://localhost:8888可以查看自动生成的测试代码运行的结果 第三步： 配置文件在 spec/javascripts/suport/jasmine.yml 可以在里面配置包含要测试的目标js文件，css文件，测试文件存放目录等一些配置； 在spec/javascripts/helpers/里面我们可以自定义一些matcher的方法，比如里面自动产生的示例：toBePlaying方法； 第四步：开始编写测试代码；下面贡献一个我的例子： js的功能代码 \[code="javascript"] function matchFail\_user(it){ $(it).next().val(''); var n = $(it).parent().next(); while(n.attr("class") == 'auto\_clean'){ wipe\_clean(\[n.children("input:first").attr('id')]); n = n.next(); } } \[/code] js功能的测试代码： \[code="javascript"] describe('matchFail\_user',function(){ afterEach(function (){ $("#workspace").remove(); }); it('set project hidden empty and wipe clean current row', function() { $("body").append("

"); workspace = $("#workspace"); workspace.html(""); bind\_autocomplete('child', {}); project = $("#projects\_iterations\_1").get(); project\_hidden = $("#projects\_iterations\_1").next(); spyOn(window,"wipe\_clean"); matchFail\_user(project) expect(project\_hidden.val()).toEqual(""); expect(window.wipe\_clean).toHaveBeenCalledWith(\[$(project).parent().next().children("input:first").attr('id')]); }); });\[/code] Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. 在这个jasmine里面的spy很经常用，比如可以如下使用： \[code="javascript"] var Klass = function () { }; Klass.staticMethod = function (arg) { return arg; }; Klass.prototype.method = function (arg) { return arg; }; Klass.prototype.methodWithCallback = function (callback) { return callback('foo'); }; ... describe("spy behavior", function() { it('should spy on a static method of Klass', function() { spyOn(Klass, 'staticMethod'); //创建一个监视Klass.staticMethod的监视器，理论上这个是不会有返回值的，因为被拦截了，它可以使用 spyOn(Klass, 'staticMethod').andReturn("result")的方法替它返回结果，也有类似的比如andCallThrough之类的方法来真正实现这个功能； Klass.staticMethod('foo argument'); expect(Klass.staticMethod).toHaveBeenCalledWith('foo argument'); }); it('should spy on an instance method of a Klass', function() { var obj = new Klass(); spyOn(obj, 'method'); obj.method('foo argument'); expect(obj.method).toHaveBeenCalledWith('foo argument'); var obj2 = new Klass(); spyOn(obj2, 'method'); expect(obj2.method).not.toHaveBeenCalled(); }); it('should spy on Klass#methodWithCallback', function() { var callback = jasmine.createSpy(); new Klass().methodWithCallback(callback); expect(callback).toHaveBeenCalledWith('foo'); }); }); \[/code] 虽然测试js很恶心，但也要测，终于写完了这些测试。。。。可以继续研究Android啦～