Ruby on rails 4 在调用Expection时,RSpec为数组抛出NoMethodError'strip'
我使用WebMock成功地测试了应用程序中的一些API调用。然而,有一项测试意外失败。失败的方法在开发中可以从控制台正常工作,但在测试中,RSpec抛出了一个异常 测试的方法是:Ruby on rails 4 在调用Expection时,RSpec为数组抛出NoMethodError'strip',ruby-on-rails-4,rspec,rspec2,Ruby On Rails 4,Rspec,Rspec2,我使用WebMock成功地测试了应用程序中的一些API调用。然而,有一项测试意外失败。失败的方法在开发中可以从控制台正常工作,但在测试中,RSpec抛出了一个异常 测试的方法是: class MyClass class << self . . . def get_internal_users response = HTTParty.get(API_URL + '/internal_users.json') return false unl
class MyClass
class << self
. . .
def get_internal_users
response = HTTParty.get(API_URL + '/internal_users.json')
return false unless response.code == 200
response.parsed_response.each { |user| user.symbolize_keys! }
end
end
end
运行此测试会引发以下异常:
Failure/Error: it { expect {subject}.to_not raise_error }
expected no Exception, got #<NoMethodError: undefined method `strip' for [{"user_name"=>"test_user"}, {"user_name"=>"test_user_2"}]:Array>
但是,我不愿意将这个gem分发到这个应用程序将部署到的所有服务器上 幸好我不知道这是一个httparty问题、webmock问题、rspec问题还是三者的合并问题。我在firebug中跟踪请求并检查响应头。我认为ContentType指示httparty如何解析响应。果不其然:
stub_request( :get, API_URL + '/internal_users.json')
.to_return( :status => 200, :body => @internal_users.to_json, :headers => {'Content-Type' => 'application/json; charset=utf-8'})
修好了。应该有人在我之前抓到的
# httparty-0.13.0/lib/httparty/parser.rb
def parse
#body is an array, the return check is throwing the exception:
# return nil if body.nil? || body.strip.empty? || body == "null"
# allow arrays:
unless body.class == Array
return nil if body.nil? || body.strip.empty? || body == "null"
end
if supports_format?
parse_supported_format
else
body
end
end
stub_request( :get, API_URL + '/internal_users.json')
.to_return( :status => 200, :body => @internal_users.to_json, :headers => {'Content-Type' => 'application/json; charset=utf-8'})