【问题标题】:[Cucumber]Ruby constants strange behavior[Cucumber]Ruby 常量的奇怪行为
【发布时间】:2018-05-28 21:08:43
【问题描述】:

我发现自己无法解释的非常奇怪的行为。看起来如果您同时使用 Cucumber 和常量,Ruby 将在场景之间保存局部变量。 在 Cucumber test.feature 文件中,我有这样的步骤

    Feature: Test

  Scenario Outline: Test outline
    Given Set data
      |user_id  |hash  |
      |<user_id>|<hash>|

    Examples:
      |user_id|hash|
      |king   |xfgh|

  Scenario Outline: What is going on
    Given Set data
      |shop_id|
      |<shop_id>|

    Examples:
      |shop_id|
      |554    |

比我有这样的steps.rb文件:

   Given(/^Set data$/) do |table|
  # table is a table.hashes.keys # => [:smth]
  temp = Constants::Cons.dup
  table.hashes[0].each do |key, values|
    temp[:bodyData][eval(":#{key}")] = values
  end
  puts("temp: #{temp}")
end

文件 cmodule.rb:

module Constants

 Cons =
 {
     :toService => "Microcontrol",
     :bodyData=>{}
 }

end

还有文件 env.rb:

require_relative 'cmodule'
World(Constants)

所以,比我运行文件 test.feature 我的输出看起来像这样:

temp: {:toService=>"Microcontrol", :bodyData=>{:user_id=>"king", :hash=>"xfgh"}}

temp: {:toService=>"Microcontrol", :bodyData=>{:user_id=>"king", :hash=>"xfgh", :shop_id=>"554"}}

所以,问题是,为什么我的第二个场景大纲会给出这样的输出:

temp: {:toService=>"Microcontrol", :bodyData=>{:user_id=>"king", :hash=>"xfgh", :shop_id=>"554"}}

而不是这样(这就是我最初从场景中所期望的):

temp: {:toService=>"Microcontrol", :bodyData=>{:shop_id=>"554"}}

但还有更多,我已经开始了一个实验并将我的 cmodule.rb 更改为:

module Constants
 def self.cons
   {
       :toService => "Microcontrol",
       :bodyData=>{}
   }
 end

end

也改了steps.rb:

Given(/^Set data$/) do |table|
  # table is a table.hashes.keys # => [:smth]
  temp = Constants.cons.dup
  table.hashes[0].each do |key, values|
    temp[:bodyData][eval(":#{key}")] = values
  end
  puts("temp: #{temp}")
end

运行 test.feature 后,我得到了:

temp: {:toService=>"Microcontrol", :bodyData=>{:user_id=>"king", :hash=>"xfgh"}}

temp: {:toService=>"Microcontrol", :bodyData=>{:shop_id=>"554"}}

所以,我想不通为什么它适用于 def 而不适用于常量?

【问题讨论】:

    标签: ruby cucumber constants


    【解决方案1】:

    如果您在步骤定义中进行调试并检查自我,您可以找到答案。以下为推测:

    当您将模块添加到 World 时,这意味着该模块的内容可用于每个步骤定义,因为在步骤定义中 self 是 World。当您将Cons 定义为常量时,您设置了一个无法更改的值。它为包含对象的生命而存在。所以Cons 在每一步定义中都将是相同的哈希值(查看对象 ID 以确认这一点)。当您使用 def 时,您正在调用该方法,因此您将在每个步骤定义中获得不同的哈希值。

    【讨论】:

    • 感谢您的回答。所以,另一个问题是:如您所见,我使用了.dup 方法,它从常量中复制值。此外,在使用.dup 时,我打印了每个tempobject_id,并且ID 每次都不同。为什么在这种情况下它的工作原理是一样的?
    • 检查重复结构中事物的对象ID,看看它们是否相同。我的回答是为您提供工具来解决正在发生的事情,我不能提供更多,这需要太多时间,抱歉。
    猜你喜欢
    • 2014-01-21
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多