Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails test for hash type

In Sinatra, I could test for some_object.class.name == "Hash". Now, after a submit, I have to test for that, plus == "ActiveSupport::HashWithIndifferentAccess", for my code to work. Why is that, and do I have to update all the places where that comparison happens, or is there an easier way? thanks

like image 794
dt1000 Avatar asked Jun 20 '12 22:06

dt1000


People also ask

What is Hash in rails?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

How to run test cases in rails?

We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case.

How do you know if something is a Hash?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .


1 Answers

From the docs on ActiveSupport::HashWithIndifferentAccess:

This class has dubious semantics and we only have it so that people can write params[:key] instead of params[‘key’] and they get the same value for both keys.

So, it's a class that inherits from Hash to allow you to pass a symbol or a string as the key and return the same value for either.

To fix (and clean up) your tests, you could just use the following:

some_object.is_a? Hash

This will return true if it's a Hash or a descendant of Hash.

like image 197
Nick Colgan Avatar answered Oct 04 '22 12:10

Nick Colgan