得到httparty undefined方法`代码&#39;对于rspec中的#<hash:0x007ff3625a4800>

时间:2016-07-21 12:52:28

标签: ruby-on-rails ruby rspec httparty exotel-api

我正在为我的第一颗宝石编写规格。但我坚持这个奇怪的错误。 我的rspec的代码是

describe '#success' do
    let(:resp) { {"TwilioResponse"=>{"SMSMessage"=>{"Sid"=>"0d1c0cbfb2b5e8f97dddb4479bdbbc6a", "AccountSid"=>"exotel_sid", "From"=>"/exotel_sid", "To"=>"1234", "DateCreated"=>"2016-07-18 15:35:29", "DateUpdated"=>"2016-07-18 15:35:29", "DateSent"=>nil, "Body"=>"test sms", "Direction"=>"outbound-api", "Uri"=>"/v1/Accounts/exotel_sid/Sms/Messages/0d1c0cbfb2b5e8f97dddb4479bdbbc6a", "ApiVersion"=>nil, "Price"=>nil, "Status"=>"queued"}}} }
    before{ allow(Generator::Exotel).to receive(:post).with("/#{Generator::configuration.sid}/Sms/send", 
      {:body => {:To => 1234, :Body => 'test sms'},:basic_auth=>{:username=>"#{Generator::configuration.sid}", :password=>"#{Generator::configuration.token}"}}).and_return(resp) }

    it 'returns response object' do  
      response = Generator::Exotel.send(:to => 1234, :body => "test sms")
      expect(response).to eq ({"Status"=>200, "Message"=>"Success"})
    end
  end

当我运行rspec时,我收到此错误

NoMethodError:
       undefined method `code' for #<Hash:0x007ff3625a4800>

这是我的response.code被称为

的地方
def handle_response(response)
  response_base = response['TwilioResponse']
  if response_base.include?('RestException')
    response_base['RestException']
  else
    {"Status" => response.code, "Message" => "Success" }
  end
end

我知道httparty会为请求创建一个response对象并返回响应代码。但我不知道如何创建一个虚拟response_code 以便我的测试用例通过。我被困在这里将近2天。有人请帮忙。我真的很喜欢ruby并且第一次写规范。任何帮助将不胜感激。

更新 - response.inspect

的结果

> Generator::Exotel.send(:to => 9030435595, :body => 'jsdhgjkdfg')

它返回以下回复

> #<HTTParty::Response:0x7fb8c02f93d0 parsed_response={"TwilioResponse"=>{"SMSMessage"=>{"Sid"=>"d6ee0650072c82941ad2f06746d14ab4", "AccountSid"=>"sinscary", "From"=>"/sinscary", "To"=>"9030435595", "DateCreated"=>"2016-07-21 19:56:07", "DateUpdated"=>"2016-07-21 19:56:07", "DateSent"=>nil, "Body"=>"jsdhgjkdfg", "Direction"=>"outbound-api", "Uri"=>"/v1/Accounts/sinscary/Sms/Messages/d6ee0650072c82941ad2f06746d14ab4", "ApiVersion"=>nil, "Price"=>nil, "Status"=>"queued"}}}, @response=#<Net::HTTPOK 200 OK readbody=true>, @headers={"content-type"=>["application/xml"], "date"=>["Thu, 21 Jul 2016 14:26:07 GMT"], "server"=>["Apache/2.2.29 (Amazon)"], "x-powered-by"=>["PHP/5.3.28"], "content-length"=>["542"], "connection"=>["Close"]}>

1 个答案:

答案 0 :(得分:2)

好的,你在嘲笑HTTParty::Response。一种方法是仅使用codeparsed_response直接模拟它:

let(:resp) do
  Struct.new(:code, :parsed_response).new(200, {"TwilioResponse"=>...})
end

另一种方法是使用:

实例化真实的HTTParty::Response
let(:resp) do
  HTTParty::Response.new(
    nil, 
    Struct.new(:code, :parsed_response)
          .new(200, {"TwilioResponse"=>...}), -> { ... }
  )
end

我会采用第一种方法。请注意,您可能需要更改handle_response

response_base = response['TwilioResponse']

response_base = response.parsed_response['TwilioResponse']