Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec match array of hashes

I have an array of hashes, which for the sake of argument looks like this:

[{"foo"=>"1", "bar"=>"1"}, {"foo"=>"2", "bar"=>"2"}] 

Using Rspec, I want to test if "foo" => "2" exists in the array, but I don't care whether it's the first or second item. I've tried:

[{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}].should include("foo" => "2")) 

But this doesn't work, as the hashes should match exactly. Is there any way to partially test each hash's content?

like image 571
Pezholio Avatar asked May 22 '14 19:05

Pezholio


2 Answers

how about?

hashes = [{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}] expect(hashes).to include(include('foo' => '2')) 
like image 111
Khoa Nguyen Avatar answered Sep 19 '22 13:09

Khoa Nguyen


Use Composable Matchers

hashes = [{"foo" => "1", "bar" => "2"}, {"foo" => "2", "bar" => "2"}] expect(hashes)   .to match([     a_hash_including('foo' => '2'),      a_hash_including('foo' => '1')   ]) 
like image 25
ilgam Avatar answered Sep 18 '22 13:09

ilgam