加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rspec未定义方法’应该收到’

发布时间:2020-12-17 04:23:37 所属栏目:百科 来源:网络整理
导读:我正在尝试使用mpecoid的rspec,但我遇到了这个错误: 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're
我正在尝试使用mpecoid的rspec,但我遇到了这个错误:
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模拟,我应该得到这个错误,但在我的情况下,我正在使用它.有任何想法吗?

解决方法

您的测试需要在示例中或阻止(它们是相同的方法):
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

上下文块用于对类似示例进行分组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读