ActionDispatch :: IntegrationTest中的Stubbing方法

时间:2015-06-17 04:53:44

标签: ruby ruby-on-rails-4 integration-testing

我正在做一些条带集成测试,我想存根/模拟一些端点。我试图这样做:

Stripe::Charge.stubs(:retrieve).returns({:balance_transaction => 40})

但我得到以下内容:

NoMethodError: undefined method `stubs' for Stripe::Charge:Class

用于存根的正确语法是什么? Rails 4,Ruby 2。

编辑:这是我的完整测试方法。基本上我的payment_succeeded webhook命中条带以检索费用及其相关的余额交易以记录交易费用。我使用stripe_mock来模拟webhook事件,但我宁愿使用标准的存根技术将其余事件删除。请注意,即使我将其更改为' stub'它会抛出相同的错误(使用存根替换存根)。

require 'test_helper'
require 'stripe_mock'

class WebhooksTest < ActionDispatch::IntegrationTest
  # called before every single test
  def setup
    StripeMock.start
  end

  # called after every single test
  def teardown
    StripeMock.stop
  end

  test 'invoice.payment_succeeded' do
    Stripe::Charge.stubs(:retrieve).returns({:balance_transaction => 40})
    event = StripeMock.mock_webhook_event('invoice.payment_succeeded', { :customer => "stripe_customer1", :id => "abc123" })
    post '/stripe-events', id: event.id
    assert_equal "200", response.code
    assert_equal 1, StripeInvoicePayment.count
    assert_equal 'abc123', event.data.object.id
  end
end

2 个答案:

答案 0 :(得分:1)

这里唯一看起来不正确的是.stubs应该是.stub

答案 1 :(得分:1)

由于您没有使用RSpec,我建议您安装mocha gem以获得完整的模拟和存根工具选择。这是一个快速入门:

# Gemfile
gem "mocha", :group => :test

# test/test_helper.rb
require "mocha/mini_test"

现在你可以像这样存根:

Stripe::Charge.stubs(:retrieve => {:balance_transaction => 40})

或者,如果你想验证方法是否实际被调用,你可以设置一个期望:

Stripe::Charge.expects(:retrieve)
  .with(:id => "abc123")
  .returns({:balance_transaction => 40})
相关问题