0
votes

I'm trying to mock Stripe like this:

stub_request(:post, "https://api.stripe.com/v1/tokens").with(
 :body => {"card" => {"number" => "4242424242424242", "exp_month"=> "12", "exp_year" => "2018", "cvc" => "123"}}
).
to_return(:status => 200, :headers => {}, :body => {
  "id" => "tok_14CgP22eZvKYlo2CkgJ6ymLE",
  "livemode" => false,
  "created" => 1404517660,
  "used" => false,
  "object" => "token",
  "type" => "card",
  "card" => {
    "id" => "card_14CgP22eZvKYlo2CcdUNvicW",
    "object" => "card",
    "last4" => "4242",
    "brand" => "Visa",
    "funding" => "credit",
    "exp_month" => 12,
    "exp_year" => 2018,
    "fingerprint" => "Xt5EWLLDS7FJjR1c",
    "country" => "US"
  }
})

I am getting a no implicit conversion of Hash into String error when I call:

token = Stripe::Token.create(:card => {
  :number => params["number"],
  :exp_month => params["expiry_month"],
  :exp_year => params["expiry_year"],
  :cvc => params["cvc"]})

It's because of the hash in body in to_return, but I don't know how to avoid the error.

If I add .to_s to the hash, I get:

Invalid response object from API: "{\"id\"=>\"tok_14CgP22eZvKYlo2CkgJ6ymLE\", \"livemode\"=>false, \"created\"=>1404517660, \"used\"=>false, \"object\"=>\"token\", \"type\"=>\"card\", \"card\"=>{\"id\"=>\"card_14CgP22eZvKYlo2CcdUNvicW\", \"object\"=>\"card\", \"last4\"=>\"4242\", \"brand\"=>\"Visa\", \"funding\"=>\"credit\", \"exp_month\"=>12, \"exp_year\"=>2018, \"fingerprint\"=>\"Xt5EWLLDS7FJjR1c\", \"country\"=>\"US\"}}" (HTTP response code was 200)

If I add a .to_json to the end, Stripe::Token passes but I get a stack error too deep error when I try to use the resulting token in any way.

What do you recommend?

1
Which bit of code is returning Invalid response object from API? :body in stub_request needs to be a String. to_json sounds like the right thing to be doing, but what error does that give?Sam Starling
Error was from token = Stripe::Token.create(:card => { :number => params["number"], :exp_month => params["expiry_month"], :exp_year => params["expiry_year"], :cvc => params["cvc"]}).steven_noble
With .to_json, Stripe::Token did not throw an error, but calling the resulting token does.steven_noble

1 Answers

0
votes

It could be that your stubbing is not returning correctly. It may help to make your stubbing a little less specific. For example:

body = {
  "id" => "tok_14CgP22eZvKYlo2CkgJ6ymLE",
  "livemode" => false
  # snip...
}

stub_request(:post, "https://api.stripe.com/v1/tokens")
  .to_return(:status => 200, :body => body.to_json)

However, it's difficult to know exactly what errors are being thrown, so I can only give vague ideas which may help. What error does calling token give you?