RSpec: how to test if a method was called?

后端 未结 4 2234
眼角桃花
眼角桃花 2020-12-13 03:00

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 o

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 03:59

    To fully comply with RSpec ~> 3.1 syntax and rubocop-rspec's default option for rule RSpec/MessageSpies, here's what you can do with spy:

    Message expectations put an example's expectation at the start, before you've invoked the code-under-test. Many developers prefer using an arrange-act-assert (or given-when-then) pattern for structuring tests. Spies are an alternate type of test double that support this pattern by allowing you to expect that a message has been received after the fact, using have_received.

    # arrange.
    invitation = spy('invitation')
    
    # act.
    invitation.deliver("foo@example.com")
    
    # assert.
    expect(invitation).to have_received(:deliver).with("foo@example.com")
    

    If you don't use rubocop-rspec or using non-default option. You may, of course, use RSpec 3 default with expect.

    dbl = double("Some Collaborator")
    expect(dbl).to receive(:foo).with("foo@example.com")
    
    • Official Documentation: https://relishapp.com/rspec/rspec-mocks/docs/basics/spies
    • rubocop-rspec: https://docs.rubocop.org/projects/rspec/en/latest/cops_rspec/#rspecmessagespies

提交回复
热议问题