Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec 2.7 and hash should have_key

Tags:

ruby

rspec

I'm trying to figure out why a very simple "does this hash have this key" spec I'm writing is failing. Going into my Ruby REPL I am trying the following...

[3] pry(main)> a_hash = {:a=>"A"}
=> {:a=>"A"}
[4] pry(main)> a_hash.should have_key :a
NoMethodError: undefined method `have_key' for main:Object
from (pry):4:in `<main>'
[5] pry(main)> a_hash.keys.length.should == 1
=> true
[8] pry(main)> a_hash.has_key? :a
=> true

The first test is obviously what I want to get working and the second test I'm running just to verify that RSpec is loaded in my REPL environment.

like image 756
cfeduke Avatar asked Nov 17 '11 23:11

cfeduke


2 Answers

You can actually have RSpec matchers outside "it" blocks. You just need to include RSpec::Matchers.

[ ~/work/mobile_server (master)]$ irb
>> require 'rspec'
true
>> include RSpec::Matchers
Object < BasicObject
>> {a: 1}.should have_key(:a)
true
like image 197
Costi Avatar answered Nov 08 '22 07:11

Costi


You need to actually do this inside an RSpec example, I don't think you can write that kind of code anywhere.

describe "" do
  it "has a key" do
     ...
  end
end
like image 42
David Grayson Avatar answered Nov 08 '22 07:11

David Grayson