Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: how to test if a method was called?

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.

like image 888
Mikey Hogarth Avatar asked Jan 21 '14 15:01

Mikey Hogarth


People also ask

How do I know if a method was called RSpec?

You can check a method is called or not by using receive in rspec.

How do I mock a method 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.

What is stub in RSpec?

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.

What is RSpec and capybara?

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.


2 Answers

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end
like image 179
wacko Avatar answered Oct 14 '22 08:10

wacko


In the new rspec expect syntax this would be:

expect(subject).to receive(:bar).with("an argument I want")
like image 43
Uri Agassi Avatar answered Oct 14 '22 06:10

Uri Agassi