2015-02-11 202 views
0

我只是想调用返回一个地址作为从继承的类的字符串,其动态地构建一个功能:方法返回功能,而不是串

class @Api 

    DEFAULT_API_VERSION: 'v2' 

    constructor: -> 
    @setVersion(@DEFAULT_API_VERSION) 
    return 

    setVersion: (version) -> 
    @version = version if version? 

    getVersion: -> 
    @version 

    baseUrl: -> 
    "http://api#{@getVersion()}.mysite.com/api/#{@getVersion()}/" 

class @ApiArticle extends Api 

    constructor: -> 
    super 
    return 

    articlesUrl: -> 
    "#{@baseUrl}news/articles".toString() 

这是在父类中的测试,其被逝水

it 'provides the baseUrl for Api calls', -> 
    api = new Api() 
    expect(api.baseUrl()).toEqual('http://apiv2.mysite.com/api/v2/') 

这是我的测试,它失败

it 'returns all news articles url', -> 
    new ApiArticle() 
    url = api_article.articlesUrl() 
    expect(url).toEqual 'http://apiv2.mysite.com/api/v2/news/articles' 

结果我从这个规范得到的,它应该是一个字符串,但收到这个:

Expected 
    'function() { return "http://api" + (this.getVersion()) + ".mysite.com/api/" + (this.getVersion()) + "/"; }news/articles' 
to equal 
    'http://apiv2.mysite.com/api/v2/news/articles'. 

有缺什么?我必须明确地渲染/计算吗?

我很新的JS和咖啡。

谢谢!

回答

2

这里

articlesUrl: -> 
    "#{@baseUrl}news/articles".toString() 

你想叫超类中的方法baseUrl,而是只提到了它。那么函数本身得到toString ed,并且“news/articles”被追加。这将导致字符串:function() { return "http://api" + (this.getVersion()) + ".mysite.com/api/" + (this.getVersion()) + "/"; }news/articles,这是您在测试错误中看到的内容。

修复它通过实际调用baseUrl,不仅仅是指它:

articlesUrl: -> 
    "#{@baseUrl()}news/articles".toString() 

然后,您可以删除无用toString电话。

你可能要考虑重新命名方法getBaseUrl,以避免再犯这样的错误。

+0

谢谢你,现在的工作也没有附加的'''的toString()''' – Jan 2015-02-11 12:32:25