Метод Rspec Undefined «должен получить»

Я пытаюсь использовать rspec с mongoid, но сталкиваюсь с этой ошибкой:

undefined method `should_receive' for ShortenedUrl:Class

Вот мой файл spec_helper.rb:

# 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

И вот мой тестовый файл:

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

Наконец, вот 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

Насколько я понимаю, я должен получить эту ошибку, если я не использовал макет rspec, но в моем случае я его использую. Любые идеи?


person Oscar Del Ben    schedule 19.12.2010    source источник


Ответы (1)


Ваш тест должен находиться внутри блока example или it (это один и тот же метод):

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

Блок context используется для группировки похожих примеров.

person Ryan Bigg    schedule 19.12.2010
comment
Я не могу поверить, что я сделал это. Спасибо! - person Oscar Del Ben; 19.12.2010
comment
Странно... Столкнулся с той же проблемой. У меня это в блоке it. Но я продолжаю получать undefined method should_receive' для Mailer:Class`. Это rspec-rails 2.10.1 - person Brian Armstrong; 08.05.2012
comment
@BrianArmstrong Создайте где-нибудь суть своего теста. - person Ryan Bigg; 09.05.2012