Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test with Rspec that a key exists inside a hash that contains an array of hashes

Tags:

ruby

hash

rspec

I have a Model method that returns the following when executed.

 {"data" => [  {"product" => "PRODUCTA", "orders" => 3, "ordered" => 6, "revenue" => 600.0},  {"product" => "PRODUCTB", "orders" => 1, "ordered" => 5, "revenue" => 100.0}]} 

I would like to test to make sure that "revenue" in the first hash is there and then test that the value is equal to 600.

subject { described_class.order_items_by_revenue }  it "includes revenue key" do   expect(subject).to include(:revenue) end 

I am completely lost on how to test this with Rspec.

like image 653
Mark Datoni Avatar asked Oct 27 '15 22:10

Mark Datoni


People also ask

How do you check if a hash contains a key?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How do I run a test in RSpec?

Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.

Is RSpec used for unit testing?

RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool.

What does RSpec describe do?

The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.


1 Answers

RSpec allows you to use the have_key predicate matcher to validate the presence of a key via has_key?, like so:

subject { described_class.order_items_by_revenue }  it "includes revenue key" do   expect(subject.first).to have_key(:revenue) end 
like image 63
Chris Heald Avatar answered Oct 02 '22 21:10

Chris Heald