Max Cascone Max Cascone - 3 months ago 8
Ruby Question

Stub helper function in chefspec

Searched all day and haven't solved this, so here goes. EDIT: the process of writing this post forced me to think about the problem differently, and I figured it out. So I'll answer my own question here. I think I checked "answer your own question".

I have a line in recipe

web.rb
that calls a helper function:

prodservice_machine_name = search_for_nodes("ProdApp_Service_Install:1 AND chef_environment:#{node_env}")[0]['fqdn']


search_for_nodes
is defined in
spec_helpers.rb
, wraps some help around a
knife
search, and returns
nodes[]


We use the response to find a node's machine name:

prodservice_machine_name = search_for_nodes("ProdApp_Service_Install:1 AND chef_environment:#{node_env}")[0]['fqdn']


I couldn't figure out how to stub
search_for_nodes
to get a usable response.

Answer

As I said above I was writing this question up, and the act of writing the question made it dawn on me what the issue was: I wasn't mocking the return in the correct format, a key-value array.

I finally came up with this:

before(:each) do
  receive(:search_for_nodes).and_return(['fqdn' => 'dummy_server'])
end

It works, and I can test that my recipe correctly uses dummy_server in the right place.

I hope this helps future searchers!

Comments