假设我在 Coffeescript 有一个类:
class MyGame
constructor: () ->
@me = new Player
@opponents = [new Player, new Player]
想在 Jasmine 中测试:
describe "MyGame", ->
beforeEach ->
window.game = new MyGame
it "should have two players", ->
expect(window.game.opponents.length).toEqual 2
但我收到错误
TypeError: Result of expression 'window.game.opponents' [undefined] is not an object.
?window.game
方法对我来说也似乎很尴尬。如果我尝试将其定义为 @game = new MyGame
我收到错误 ReferenceError: Can't find variable: MyGame
但我想这与 Coffeescript 的包装方式有关?更新:该问题似乎更像是如上所述的引用问题。我正在运行
guard-jasmine
看起来像guard 'jasmine', :all_on_start => false, :all_after_pass => false do
watch(%r{app/assets/javascripts/(.+)\.(js\.coffee|js)}) { |m| "spec/javascripts/#{m[1]}_spec.#{m[2]}" }
watch(%r{spec/javascripts/(.+)_spec\.(js\.coffee|js)}) { |m| "spec/javascripts/#{m[1]}_spec.#{m[2]}" }
watch(%r{spec/javascripts/spec\.(js\.coffee|js)}) { "spec/javascripts" }
end
和我的
jasmine.yml
文件有:src_files:
- "app/assets/**/*.js"
- "app/assets/**/*.coffee"
spec_files:
- '**/*[sS]pec.js.coffee'
asset_pipeline_paths:
- app/assets
- spec/javascripts
我得到一个
ReferenceError: Can't find variable: MyGame
所以我认为这要么是 Rails 3.1 Assets 管道的东西,要么是 Coffeescript 包装对象的方式。
最佳答案
尝试使用 @
定义您的 CoffeeScript 类运算符:
class @MyGame
constructor: () ->
@me = new Player
@opponents = [new Player, new Player]
这将允许您从任何地方访问该类,例如从您的 jasmine 测试中,并且您可以避免将测试变量附加到窗口:
describe "MyGame", ->
beforeEach ->
@game = new MyGame
it "should have two players", ->
expect(@game.opponents.length).toEqual 2
这样做的原因是,coffeescript 通过将所有内容包装在闭包中来避免引入全局变量。不幸的是,这对于面向对象的代码可能是不可取的。使用
@
运算符将类定义附加到全局 this(即窗口)上,因此您可以根据需要实例化您的类。你现在可能在你的全局空间里有一些全局变量,你的类,但对我来说这是一个不错的权衡。希望这可以帮助!
关于ruby-on-rails-3 - 使用 Jasmine 和 Rails 3.1 测试 Coffeescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7991554/