如何模拟重定向到外部API的控制器的响应?

时间:2013-05-13 13:49:52

标签: ruby-on-rails ruby rspec

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

这是PaymentGateway对象重定向到的URL。如何让我的测试认为支付网关返回了响应?实际上,它没有。根据他的选择,它可能会也可能不会返回用户。这类似于使用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)>'

1 个答案:

答案 0 :(得分:3)

您可以使用诸如WebMock之类的gem来存根并设置远程HTTP请求的期望。

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

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