【问题标题】:Rspec Undefined method 'should receive'Rspec未定义的方法'应该接收'
【发布时间】:2010-12-19 09:18:47
【问题描述】:

我正在尝试将 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 模拟,我应该会收到此错误,但就我而言,我正在使用它。有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails rspec mongoid


    【解决方案1】:

    您的测试需要在 exampleit 块内(它们是相同的方法):

    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 块用于对相似示例进行分组。

    【讨论】:

    • 我不敢相信我做到了。谢谢!
    • 奇怪...我遇到了同样的问题。我把它放在it 块中。但我不断收到undefined method should_receive' for Mailer:Class`。这是 rspec-rails 2.10.1
    • @BrianArmstrong 在某处创建你的测试要点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多