如何模拟重定向到外部 API 的控制器的响应? [英] How do I mock a response of a controller that redirects to an external API?

查看:47
本文介绍了如何模拟重定向到外部 API 的控制器的响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的orders_controller 需要将订单转发到支付网关.它使我的测试失败:No route matching [GET] "/v2/checkout/payment.html"

My orders_controller needs to forward an order to a payment gateway. It's making my tests fail: No route matches [GET] "/v2/checkout/payment.html"

这是 PaymentGateway 对象重定向到的 URL.我怎样才能让我的测试认为支付网关返回了响应?事实上,事实并非如此.根据用户的选择,它可能会也可能不会返回用户.这类似于使用 Paypal 付款.

That's is the URL that the PaymentGateway object redirects to. How can I trick my tests into thinking that the payment gateway returned a response? In reality, it doesn't. It may or may not return the user depending on his choice. It's similar to paying with Paypal.

  def create
    @order = current_user.orders.build(params[:order])
    @order.add_line_items_from_cart(current_cart)
    if @order.save
      destroy_cart current_cart
      payment = PaymentGateway.new(@order).send
      redirect_to payment
    else
      render 'new'
    end
  end


feature 'User creates an order with valid info' do

  background do
    setup_omniauth_user
    visit root_path

    create(:line_item, cart: Cart.last)

    click_link 'cart-link'
    click_link 'th-checkout-link'
  end

  scenario 'an order is created and cart is deleted' do
    cart = Cart.last
    fill_in_order

    expect {
      click_button "Submit"
    }.to change(Order, :count)

    cart.reload.should be_nil
  end
end



User creates an order with valid info an order is created and cart is deleted
     Failure/Error: click_button "Submit"
     ActionController::RoutingError:
       No route matches [GET] "/v2/checkout/payment.html"
     # ./spec/features/orders_spec.rb:64:in `block (3 levels) in <top (required)>'
     # ./spec/features/orders_spec.rb:63:in `block (2 levels) in <top (required)>'

推荐答案

你可以使用一个 gem,比如 WebMock 存根并设置远程 HTTP 请求的期望值.

You can use a gem such as WebMock to stub and set the expectation for remote HTTP requests.

我用它来模拟支付网关 &单点登录身份验证.这是一个语法用法示例,尽管您显然需要更新正文以反映应该返回的内容.

I use this to mock payment gateways & single sign-on authentication. Here is an example of syntax usage, although you will obviously need to update the body to reflect what should be returned.

stub_request(:any, "http://example.com/v2/checkout/payment.html").to_return(
  :body => "SUCCESS",
  :status => 200,
  :headers => { 'Content-Length' => 3 }
)

这篇关于如何模拟重定向到外部 API 的控制器的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆