Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec Undefined method 'should receive'

I'm trying to use rspec with mongoid but I'm running across this error:

undefined method `should_receive' for ShortenedUrl:Class

Here's my spec_helper.rb file:

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  # == Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
  config.mock_with :rspec

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  # config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  # config.use_transactional_fixtures = true

  config.before(:each) do
    Mongoid.master.collections.each(&:drop)
  end
end

And here's my test file:

require 'spec_helper'

describe UrlsController do

  describe "POST make_short" do

    context "when posting a valid url" do
      # url = mock('ShortenedUrl')
      url = Struct.new('ShortenedUrl')
      ShortenedUrl.should_receive(:new).with(:url => 'http://example.com').and_return(url)
      url.should_receive(:save!)

      post :make_short, :url => 'http://example.com'
    end

  end

end

Finally, here's the Gemfile:

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem "mongoid", ">= 2.0.0.beta.19"
gem "rspec-rails", ">= 2.0.1", :group => [:development, :test]
gem "cucumber-rails", :group => :test
gem "capybara", :group => :test

From what I understand, I should get this error if I wasn't using the rspec mock, but in my case I'm using it. Any ideas?

like image 280
Oscar Del Ben Avatar asked Dec 19 '10 09:12

Oscar Del Ben


1 Answers

Your test needs to be inside an example or it block (they're the same method):

it "when posting a valid url" do
  # url = mock('ShortenedUrl')
  url = Struct.new('ShortenedUrl')
  ShortenedUrl.should_receive(:new).with(:url => 'http://example.com').and_return(url)
  url.should_receive(:save!)

  post :make_short, :url => 'http://example.com'
end

A context block is used for grouping similar examples.

like image 199
Ryan Bigg Avatar answered Sep 28 '22 07:09

Ryan Bigg