【问题标题】:How to test correctness of arguments sent to external API如何测试发送到外部 API 的参数的正确性
【发布时间】:2014-01-26 13:17:25
【问题描述】:

我有外部 API 端点,比如说:http://www.fake_me_hard.com/api。我想从我的应用程序中对此进行一些调用。 Endpoint 接受以下结构作为参数:

  {   
  :amount => amount, 
  :backurl => root_path,
  :language => locale,
  :orderid => order_id, 
  :pm => payment_method, 
  :accept_url => "/payment/success", 
  :exception_url  =>  "/payment/failure", 
 }

负责收集此哈希的方法是EndpointRequestCollector.give_me_hash。 我应该如何测试give_me_hash 是否返回正确的结构?

我也可以使用相同的策略在 specsclass 中创建此结构:

class EndpointRequestsCollector
  def self.give_me_hash
    {
       #....collecting hash #1
    }
  end
end

describe EndpointRequestCollector do
  context '.give_me_hash' do
    it 'returns proper structure' do
      expect(described_class.give_me_hash).to eq(
        {
          #... collecting hash #2
        }
       )
    end
  end
end

...但它会在 2 个地方重复相同的代码,并且不会测试任何东西。

你知道解决这个问题的好方法吗?

【问题讨论】:

  • 我不理解你的问题

标签: ruby-on-rails ruby unit-testing rspec


【解决方案1】:

这是我通常测试我的 json api 的方式:

如果只是想测试格式,可以使用includematcher:

    %w(my awesome keys).each do |expected_key|
      expect(described_class.give_me_hash.keys).to include(expected_key)
    end

通过这样做,您可以保证格式是正确的,直到有人破坏您的方法。

如果你想测试返回的值,你可以使用类似的东西:

   let(:correct_value) { 42 }

   it 'must have correct value' do 
     expect(described_class.give_me_hash[key]). to eq correct_value
   end

但我建议您将此逻辑分开以将值传递给另一个方法,并为此进行另一个测试。

【讨论】:

    【解决方案2】:

    也许:

    let(:args) {["amount", "backurl", "language", "orderid", "pm", "accept_url", "exception_url"]}
    #...
    it 'returns proper structure' do
      described_class.give_me_hash.each_key do |key|
        expect(key).to satisfy{|key| args.include?(key)}
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 2016-07-19
      • 2021-03-19
      • 1970-01-01
      相关资源
      最近更新 更多