Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

with not working as expected. #523

Closed
aaricpittman opened this issue Mar 16, 2022 · 3 comments
Closed

with not working as expected. #523

aaricpittman opened this issue Mar 16, 2022 · 3 comments
Assignees

Comments

@aaricpittman
Copy link

I have a tree structure and wrote a method crawl that takes a block. For each node in the tree, it will call the block passing it the node, the node's parent, and the level. I'm trying to write a test for this method and have the following.

prc = Proc.new {}
prc.expects(:call).once.with(subject, nil, 0)
prc.stubs(:call)

subject.crawl(&prc)

This fails with a expected exactly once, invoked never message. So, I tried to rewrite using the with block syntax like so.

prc = Proc.new {}
prc.expects(:call).once.with { |node, parent, level| node == subject && parent == nil && level == 0 }
prc.stubs(:call)

subject.crawl(&prc)

And I got the same failure. I tried placing a binding.pry inside the with block and verified that the node == subject && parent == nil && level == 0 statement returns true.

What am I doing wrong?

@floehopper
Copy link
Member

Hi. This is relatively common source of confusion e.g. #171.

From this section of the README:

When a method is invoked on a mock object, the mock object searches through its expectations from newest to oldest to find one that matches the invocation. After the invocation, the matching expectation might stop matching further invocations.

And from the "gotchas" in the documentation for Mocha::Mock:

if you create an expectation and then a stub for the same method, the stub will always override the expectation and the expectation will never be met.

In your case, the stub is the newest and so matches before the expectation. And since it's a stub with no expected invocation count the matching will never be exhausted. So the expectation will never be invoked and thus is never satisfied.

Does that help?

@floehopper floehopper self-assigned this Mar 16, 2022
@aaricpittman
Copy link
Author

@floehopper thanks for your help. that helped me fix it.

@floehopper
Copy link
Member

You're welcome! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants