Search code examples
ruby-on-railsrspecrspec-rails

Why do I get "#to_hash is deprecated. Use #to_h instead" when testing with RSpec?


I'm starting with Rails, and I'm trying to get used to RSpec writing some tests. In this particular example, I'm trying to test a class that performs calls to twitter api. As it has a small ad-hoc cache, I'm trying to test that the API is only called when it's necessary or that it returns the currect kind of object.

I'm using a Ruby Twitter client.

before do
    @manager = TwitterService.new
    @manager.client = double()
    hash = JSON.parse('{"id":4}', :symbolize_names => true)
    allow(@manager.client).to receive(:friends) { [Twitter::User.new(hash)] }
end

it 'returns a collection of friends' do
  @result.each do |r|
    expect(r).to be_a Twitter::User 
  end
end

As far as I've been able to see, no error or warnings are being thrown in execution, but when I run rspec I get:

/home/myuser/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.1/lib/active_support/core_ext/object/json.rb:48:in `as_json': 
[DEPRECATION] #to_hash is deprecated. Use #to_h instead.

I don't even see where to_hash is being used. I guess that it can be internally used by JSON.parse but if that was true, I don't know how to change that. Even everything seems to work, these warnings affect heavily to tests readability.


Solution

  • Yes, probably your JSON.parse is using the as_json function internally, and it calls to_hash. On rails' source code it's actually like this:

    class Object
      def as_json(options = nil) #:nodoc:
        if respond_to?(:to_hash)
          to_hash.as_json(options)
        else
          instance_values.as_json(options)
        end
      end
    end
    

    I suppose you could monkeypatch that, if that's critical to you, and check rails' issues on github, to either follow how it's going or create one yourself.