Search code examples
ruby-on-railsrspecrspec-rails

Why isn't it possible to add RSpec stub methods to this object?


For some reason RSpec stubbing isn't available in my tests and I can't figure out why.

Here's an example test:

RSpec.describe User, type: :model do 
  it "Should allow me to stub a model" do
    u = User.new
    u.stub(:test)
    u.test
  end
end

and here's the test result:

Failures:

  1) Subscription Should allow me to stub a model
     Failure/Error: u.stub(:test)
     NoMethodError:
       undefined method `stub' for #<User:0x007fa5cfea20c8>
     # ./spec/models/user_spec.rb:6:in `block (2 levels) 
     in <top (required)>'

FWIW the mock config section of my spec helper file is as follows:

config.mock_with :rspec do |mocks|
  # Enable only the newer, non-monkey-patching expect syntax.
  # For more details, see:
  #   - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
  mocks.syntax = :expect

  # Prevents you from mocking or stubbing a method that does not exist on
  # a real object. This is generally recommended.
  mocks.verify_partial_doubles = true
end

Solution

  • The old syntax is accessible with mocks.syntax = :should. However, you can use new: allow(u).to receive(:test)