When writing RSpec tests, I find myself writing a lot of code that looks like this in order to ensure that a method was called during the execution of a test (for the sake of argument, let's just say I can't really interrogate the state of the object after the call because the operation the method performs is not easy to see the effect of).
describe "#foo"
it "should call 'bar' with appropriate arguments" do
called_bar = false
subject.stub(:bar).with("an argument I want") { called_bar = true }
subject.foo
expect(called_bar).to be_true
end
end
What I want to know is: Is there a nicer syntax available than this? Am I missing some funky RSpec awesomeness that would reduce the above code down to a few lines? should_receive
sounds like it should do this but reading further it sounds like that's not exactly what it does.
You can check a method is called or not by using receive in rspec.
Mocking with RSpec is done with the rspec-mocks gem. If you have rspec as a dependency in your Gemfile , you already have rspec-mocks available.
In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.
Capybara and RSpec can be categorized as "Testing Frameworks" tools. Capybara and RSpec are both open source tools. It seems that Capybara with 8.85K GitHub stars and 1.29K forks on GitHub has more adoption than RSpec with 2.53K GitHub stars and 202 GitHub forks.
it "should call 'bar' with appropriate arguments" do
expect(subject).to receive(:bar).with("an argument I want")
subject.foo
end
In the new rspec
expect
syntax this would be:
expect(subject).to receive(:bar).with("an argument I want")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With