2012-07-12 60 views
1

我有特点文件api_extensions.rb /支持:黄瓜:支持文件中定义的实例变量没有被传递到步骤定义

require 'rubygems' 
require 'mechanize' 
require 'json' 

module ApiExtensions 

    def initialize 
     @agent = Mechanize.new 
     @api_header = {'Accept' => 'application/json', 'Content-Type' => 'application/json'} 
     @api_uris = { 
      'the list of campuses' => 'http://example.com/servicehosts/campus.svc', 
      'the list of settings' => 'http://example.com/servicehosts/setting.svc', 
      'login' => 'http://example.com/servicehosts/Student.svc/login', 
     }  
    end 
end 

World(ApiExtensions) 

不过,我仍然得到错误undefined method '[]' for nil:NilClass (NoMethodError)上的第二行步定义文件当我运行黄瓜:

When /^I attempt to log in using a valid username and password$/ do 
    api_uri = @api_uris['login'] 
    request_body = {:username => "[email protected]", :password => "testsecret"}.to_json 
    @page = @agent.post(api_uri, request_body, @api_header) 
end 

为什么实例变量@api_uris没有显示出来,即使我已经加入了模块的世界?另外,我已经测试了通过向该文件添加一些检测工具来执行该模块,因此@api_uris正在设置中,它仅用于我的步骤定义。

最后,如果我明确指出include ApiExtensions作为我的步骤定义文件的第一行,它可以正常工作。但我认为呼吁World(ApiExtensions)应该自动将我的模块包含在所有步骤定义文件中。

谢谢!

回答

3

问题:我的理解是,World(ApiExtensions)正在扩展世界对象(请参阅https://github.com/cucumber/cucumber/wiki/A-Whole-New-World)。此扩展将使ApiExtensions方法(即您的initialize())现在可用于您的步骤。在实例变量被创建之前,您仍然需要实际调用初始化方法,并可用于所有步骤。如果您在步骤开始时添加initialize,那么您的步骤应该起作用。

解决方案: 如果要初始化这些实例变量扩大世界的时候,你应该将模块更改为:

module ApiExtensions 
    def self.extended(obj) 
     obj.instance_exec{ 
      @agent = Mechanize.new 
      @api_header = {'Accept' => 'application/json', 'Content-Type' => 'application/json'} 
      @api_uris = { 
       'the list of campuses' => 'http://example.com/servicehosts/campus.svc', 
       'the list of settings' => 'http://example.com/servicehosts/setting.svc', 
       'login' => 'http://example.com/servicehosts/Student.svc/login', 
      } 
     } 
    end 
end 

当世界对象与你的模块延伸的self.extended(obj)方法立即运行并初始化所有变量,使其可用于所有步骤。