0

How do I correctly return the hash object from the stub so that I don't always get the error message "NoMethoderror: undefined method 'each' for nil: NilClass"?

# ruby code to test
env_json = JSON.parse(Chef::ServerAPI.new.get("test").to_json)
env_json ['versions'].each do |name, version|
  # things to do
end

Within my tests, I want to mock the serverAPI call.

before(:each) do
  query = double
  allow(query).to receive(:get) do |arg1|
    case arg1.downcase
    when %r{\test}
     {"versions" => { "flag2" => false } } ## return hash value
    else
     {"versions2" => { "flag2" => true } } ## return hash value
    end
  end
  allow(Chef::ServerAPI).to receive(:new).and_return(query) 
end

Does anyone have an idea how I have to pass the hash value in the query?

user5580578
  • 1,134
  • 1
  • 12
  • 28
  • Not sure what the exact issue is but what I can tell you is that your regex for "test" is actually looking for a [tab] character followed by "est". – engineersmnky Jul 27 '21 at 18:14
  • What is the output of `JSON.parse(Chef::ServerAPI.new.get("test").to_json)` error indicates that `['versions']` returns nil Small tip: try this notation is much clearer `{ versions: { flag2: false } }` – J.Krzus Jul 27 '21 at 20:28

0 Answers0