Search code examples
ruby-on-railsruby-on-rails-3rspecrspec2rspec-rails

Needing to call stub() and should_receive() in rspec for a view partial spec


I have been having some confusion with should_receive() in rspec (v2.8)

My understanding was that it both stubbed the method - just like stub() does - and sets the expectation that this stubbed method will be called.

However, whilst trying to use it to stub out a helper method being called from a view partial, I kept getting the error:

Failure/Error: render 'invitations/header'
 ActionView::Template::Error:
   undefined method `require_javascript' for #<#<Class:0x7fe21d03d9f8>:0x7fe21cfd0c40>

In the end, I had to add in a stub() method as well to make the test succesfully pass. This code is shown below - when I remove the before block, I get the errors shown above.

describe 'invitation/header' do

  before do
    view.stub(:require_javascript)  # Why is this required ?!
  end                                                           

  it "should initialize the expandable section javascript" do
    view.should_receive(:require_javascript).with('expandable_section')
    render 'invitations/header'
  end

  ...
end

Note that I have many other tests in this file, none of which require the stub() method to successfully pass. So I am confused why I need it in this situation ?


Solution

  • When you remove that stub your test is failing because it expects that view.should_receive(:require_javascript).with('expandable_section').

    Stubbing means you are basically ghosting a method call. When you render the view your "stub" acts as if that method would actually return something.

    You can read more here: https://relishapp.com/rspec/rspec-mocks/v/2-4/docs/method-stubs