I’m just finishing my first year writing production code in Rails, and I’m not really stuck here, but the non-rubyness of what I’m experiencing is weird, and I wanted to see if anyone had this problem.
Say you’re writing code which involves an external API, so the calls you make to that API need to be carefully crafted. In order to make sure these calls are happening correctly, I want to write some specs which mandate that these calls only happen a certain a number of times and with certain arguments. Something like this:
it "only calls the wrapper once with the correct arguments" do
expect(Wrapper).to have_received(:do_magic).once
expect(Wrapper).to have_received(:do_magic).with(flowers_in_sleeve: false)
end
But having two expectations is bad practice! I use RuboCop to lint (and I like sticking to it’s conventions) so there are two options for me: either break this into two expectations or disable the rule for having multiple expectations in a block.
So, this isn’t a totally earth shattering problem. But it seems very strange to me that RSpec doesn’t have a more convenient way to satisfy this case. Maybe I just need to suck it up and write the two expectations. My goal is to do this in one expectation if possible.
This was the main solution I thought of:
it "only calls the wrapper once with the correct arguments" do
expect(Wrapper).to have_received(:do_magic).once.with(flowers_in_sleeve: false)
end
But that allows many calls to the wrapper, so long as you call the method at least once with those arguments. Which, really, if you look at the sentence you wrote:
I expect wrapper to be called once with flowers in sleeve to be false
This behavior makes sense, because I’m not saying:
I expect wrapper to be called only once with flower in sleeve to be false
.
Louis Pate is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.