【问题标题】:Test that hash contains specific keys and that values for those keys are not nil测试哈希是否包含特定键并且这些键的值不为零
【发布时间】:2017-11-03 14:41:27
【问题描述】:

如何使用 RSpec 测试方法是否返回包含特定键的哈希并且这些键的值不为零?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    我会写:

    describe MyObject do
      describe "#my_method" do
        subject(:my_method) { MyObject.new.my_method }
    
        it { is_expected.to be_a_kind_of(Hash) }
        specify { expect(my_method.keys).to include(:key1, :key2) }
        specify { expect(my_method.values).not_to include(nil) }
      end
    end
    

    您可能必须使用逗号“key1”、“key2”中的键。否则可能会抛出错误。

    【讨论】:

      【解决方案2】:

      类似这样的:

      test_method.values_at("key1", "key2").should_not include(nil)
      

      【讨论】:

      • 如果哈希值之一实际上是nil,这将不起作用。 hash.keys.should =~ [:key1, :key2] 应该可以解决问题。
      猜你喜欢
      • 2015-05-15
      • 2012-08-10
      • 2014-11-26
      • 1970-01-01
      • 2016-07-11
      • 2018-06-10
      • 2015-06-28
      • 1970-01-01
      • 2019-08-07
      相关资源
      最近更新 更多