【发布时间】:2016-07-21 12:52:27
【问题描述】:
我正在为我的第一颗宝石编写规格。但我被这个奇怪的错误困住了。 我的 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"]}>
【问题讨论】:
-
您可能在某个地方调用
xxx.code,其中xxx 是一个哈希值,您应该调用xxx[:code]。请提供一个最小、完整和可验证的示例:stackoverflow.com/help/mcve -
是的@Yule 我在我的代码中调用
response.code,我在其中发出发布请求。我已经更新了我的问题。 -
我按照你的建议尝试了
xxx[:code],但它返回nil,因为哈希中没有这样的键。 -
请在
handle_response方法的最开始写一行puts response.inspect并分享将要打印的内容。 -
@mudasobwa 添加了
response.inspect的结果
标签: ruby-on-rails ruby rspec httparty exotel-api