I am very new to Rspec and was trying to test a Ruby script (Its a Chef recipe) with the following skeleton.
def foo1
# do stuff
list_of_names # returns a list
end
def foo2(list_of_names)
# do stuff
counter = [...]
.
.
counter_by_name_hash # returns a hash
end
def main
list = foo1
counter_by_name_hash = foo2(list)
end
main
I want to assert that the function foo2 returns an empty hash when an empty list is passed as argument and a non-empty hash when a valid non empty list is passed to it.
I tried the following two ways:
First: Here I get the NoMethodError - undefined method foo2 error. Not sure how to declare subject
since the method foo2 is not within a class, its in a Ruby script which runs as a Chef recipe.
it 'has valid list of names as input and returns valid hash' do
valid_hash = {...}
expect(subject.foo2(valid_list_of_names)).to eq(valid_hash)
end
Second: Not sure if this is asserting the return value since it does not throw error even when I specify an unexpected value in the and_return part.
it 'has valid list of names as input and returns valid hash' do
valid_hash = {...}
expect(subject).to receive(:foo2).with(valid_list_of_names).and_return(valid_hash)
subject.foo2(valid_list_of_names)
end
My question really is that what is the correct way to assert the return value of the function foo2 and how should I declare Subject in my spec file if the method foo2 is not within a Ruby class but in a Recipe? Any input or help is appreciated.