-4

我一直在学习咖啡脚本,作为学习它的练习,我决定使用 TDD Conway 的 Game of Life。我选择的第一个测试是创建一个 Cell 并查看它是死的还是活的。为此,我创建了以下咖啡脚本:

class Cell 
  @isAlive = false


  constructor: (isAlive) ->
    @isAlive = isAlive

  die: ->
    @isAlive = false

然后我使用以下代码创建一个 Jasmine 测试文件(这是故意失败的测试):

Cell = require '../conway'

describe 'conway', ->
  alive = Cell.isAlive
  cell = null

  beforeEach ->
    cell = new Cell()

 describe '#die', ->
   it 'kills cell', ->
     expect(cell.isAlive).toBeTruthy()

但是,当我在 Jasmine 中运行测试时,出现以下错误:

cell is not defined

和堆栈跟踪:

1) kills cell
   Message:
     ReferenceError: cell is not defined
   Stacktrace:
     ReferenceError: cell is not defined
    at null.<anonymous> (/Users/gjstocker/cscript/spec/Conway.spec.coffee:17:21)
    at jasmine.Block.execute (/usr/local/lib/node_modules/jasmine-node/lib/jasmine-node/jasmine-2.0.0.rc1.js:1001:15)

当我执行coffee -c ./spec/Conway.spec.coffee并查看生成的 JavaScript 文件时,我看到以下内容(第 17 行,第 21 列是错误):

// Generated by CoffeeScript 1.3.3
(function() {
  var Cell;

  Cell = require('../conway');

  describe('conway', function() {
    var alive, cell;
    alive = Cell.isAlive;
    cell = null;
    return beforeEach(function() {
      return cell = new Cell();
    });
  });

  describe('#die', function() {
    return it('kills cell', function() {
      return expect(cell.isAlive).toBeTruthy(); //Error
    });
  });

}).call(this);

我的问题是,据我所知,cell 定义。我知道我错了(因为SELECT is not broken),但我试图找出我搞砸的地方。我如何用咖啡脚本诊断这个错误并找出我哪里出错了?

我研究了许多coffeescript应用程序中包含的源代码,包括这个,但源代码的格式完全相同,声明相同。

4

1 回答 1

4

这是一个缩进问题,这是您的解决方法

Cell = require '../conway'

describe 'conway', ->
  alive = Cell.isAlive
  cell = null

  beforeEach ->
    cell = new Cell()

  describe '#die', ->
    it 'kills cell', ->
      expect(cell.isAlive).toBeTruthy()

如果您查看已编译的 JavaScript,您有一个describe块,并且其中有一个块beforeEach。但是你的下一个describe街区(你在第一个街区里面)实际上并不在里面——它在外面。

这是因为第二个缩进describe只有一个空格,而不是两个。

于 2012-08-20T03:01:17.287 回答