黄瓜中未初始化的常量(NameError) - 如何将类包含在_steps.rb中?

时间:2013-11-18 21:04:31

标签: ruby cucumber

如果你觉得这是2年前提出的重复问题,我先道歉。但是我尝试了stackoverflow的各种答案,或者搜索了stackoverflow的一面,它对我来说无效。

我的问题与现有的问题几乎相同:未初始化的常量(NameError)问题 - 如何包含类? Uninitialized constant (NameError) problem - how to include a class?

我的目录结构是:

myacc/features/account_bill.feature
myacc/features/step_definitions/account_bill_steps.rb
myacc/features/support/env.rb

myacc/lib/domain_layer.rb

在env.rb中:我提出了各种解决方案

require File.join(File.dirname(__FILE__),'..', '..', 'lib', 'domain_layer')
require File.expand_path(File.dirname(__FILE__) + "/../../lib/domain_layer")

$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
$: << File.dirname(__FILE__)+'/../../lib/'

require 'domain_layer'

在我的domain_layer.rb中,我写道:

module Domain_Layer
class Account
    attr_accessor :accountid, :service_address, :full_name, :telephone, :email

    def initialize(accountid)
      @accountid = accountid
    end

  end #class

class MyAccount_Web < Account
    def account_number(id)
      return @accountid = id
    end
end #class
end #module

在步骤定义文件中,我写道:

Given(/^the account (\d+) has one to five previous bills$/) do |accountid|
  @web_account = MyAccount_Web.new(accountid)
end

当我在项目“myacc”的根目录中运行命令行时:

cucumber -verbose

我失败了:

C:\myacc01>cucumber -verbose
Code:
  * features/support/env.rb
  * features/step_definitions/account_bill_steps.rb

Features:
  * features/account_bill.feature
  * features/account_bill_1.feature
Parsing feature files took 0m0.027s
...
Given the account 03147102942 has one to five previous bills
    uninitialized constant MyAccount_Web (NameError)

从黄瓜的输出,我可以看到黄瓜只是不通过env.rb中声明的文件夹,忽略lib目录中的所有.rb文件,忽略lib目录中所需的domain_layer.rb。

我尝试将所有.rb文件复制到step_definitions文件夹中,但仍无效:

myacc/features/account_bill.feature
myacc/features/step_definitions/account_bill_steps.rb
myacc/features/step_definitions/domain_layer.rb
myacc/features/support/env.rb

myacc/lib/domain_layer.rb

结果:

C:\myacc01>cucumber -verbose
Code:
  * features/support/env.rb
  * features/step_definitions/account_bill_steps.rb
  * features/step_definitions/customer_account_bill.rb
  * features/step_definitions/domain_layer.rb
  * features/step_definitions/web_service_layer.rb

Features:
  * features/account_bill.feature
  * features/account_bill_1.feature
Parsing feature files took 0m0.028s
...
Scenario: The account has one to five previous months bills
  Given the account 03147102942 has one to five previous bills
    uninitialized constant MyAccount_Web (NameError)

我的环境是红宝石1.8.7,黄瓜1.2.1。我假设我对互联网上的所有查询结果做了我应该做的一切,是这个版本/环境问题,还是我的代码错了?

由于

1 个答案:

答案 0 :(得分:0)

如果您的类在模块内定义,您必须像这样访问它:

Domain_Layer::MyAccount_Web

同时从类和模块名称中删除下划线(这是一种命名约定)。

之后,清理您的env.rb。简单的require "domain_layer"应该足够了,因为lib文件夹会自动添加到加载路径中。