2013-05-13 46 views
1

我的orders_controller需要將訂單轉發到支付網關。這使我的測試失敗:No route matches [GET] "/v2/checkout/payment.html"如何模擬重定向到外部API的控制器的響應?

這就是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)>' 
+0

貝寶提供了一個沙箱環​​境。否則你可以嘲笑反應。 – 2013-05-13 13:52:01

+0

我沒有使用PayPal。 :/ – dee 2013-05-13 13:52:28

+0

我的錯誤,所以嘲笑響應並將其返回。 – 2013-05-13 13:53:56

回答

3

可以使用寶石如WebMock存根,併爲遠程HTTP請求的期望。

我用它來模擬支付網關&單點登錄認證。這裏是一個語法用法的例子,雖然你顯然需要更新正文以反映應該返回的內容。

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

謝謝!我發現很難看出它是如何工作的,用'expect期望{提交' } .to改變(Order,:count)'儘管...我應該在哪裏添加請求stubb? – dee 2013-05-13 14:24:28

+0

您可以像添加任何其他存根一樣添加請求存根,無論是在setup/before塊還是在單個測試本身內。一旦配置,它將攔截對該特定URL的任何請求並返回指定的響應。 – 2013-05-13 14:34:46

+1

查看此演示文稿瞭解更多詳情http://www.slideshare.net/bartoszblimke/tdd-of-http-clients-with-webmock – 2013-05-13 14:38:03