Mocha Mock进行另一项测试

我一直在遵循15个TDD步骤来创建Rails应用程序指南 – 但是遇到了一个我似乎无法解决的问题。 对于WordsController的function测试,我有以下代码:

class WordsControllerTest < ActionController::TestCase test "should get learn" do get 'learn' assert_response :success end test "learn passes a random word" do some_word = Word.new Word.expects(:random).returns(some_word) get 'learn' assert_equal some_word, assigns('word') end end 

在Word类中,我有以下代码:

 class Word < ActiveRecord::Base def self.random all = Word.find :all all[rand(all.size)] end end 

当我运行测试时,我遇到以下错误(为简洁起见缩短):

 1) Failure: unexpected invocation: Word(...).random() satisfied expectations: - expected exactly once, already invoked once: Word(...).random() 

我已经尝试过更改测试顺序以及其他许多内容,但是我一次又一次地继续接收相同的测试失败 – 已经调用了Word.random()。

我正在运行Rails 3.0 beta 4和Mocha 0.9.8。 我一直在努力寻找解决问题的方法,但我似乎无法找到它。 我是Ruby / Rails的新手,所以我对语言和框架并不熟悉。

提前致谢!

我有同样的问题,模拟function没有被隔离到测试,它似乎是摩卡的加载顺序的问题。

我有一些问题让Mocha与Rails3一起工作。 我找到了一些stackoverflowpost,但直到我在agoragames.com上发现post时才发现这个问题。

基本上,在项目的Gemfile中,Mocha的需求应如下所示:

 gem 'mocha', :require => false 

然后在test/test_helper.rb ,为mocha添加一个require行:

 ... ... require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require 'mocha' class ActiveSupport::TestCase ... ... 

我认为Gemfile中mocha的需求行意味着你需要已经安装了mocha作为gem,bundler将不会为你处理它。

摩卡需要最后加载。 我也在努力解决这个问题。

 #Gemfile group :test gem 'mocha', '~>0.9.8', :require => false ... end 

 test_helper.rb .... #at the very bottom require 'mocha' 

你怎么要摩卡? 你在使用捆绑包吗? 听起来好像摩卡拆机挂钩没有被调用?

此外,似乎没有使用rails31调用mocha_teardown。 设置的模拟永远不会被删除…(这个额外的黑客修复它)

  class ActiveSupport::TestCase def teardown super Mocha::Mockery.instance.teardown Mocha::Mockery.reset_instance end end 

这些解决方案对我自己不起作用,使用Ruby 2.2.2,Rails 4.2.2,mocha 1.1.0,shoulda-context 1.2.1,factory_girl_rails 4.5.0和一些测试相关的gem。

它还在test_helper.rb的底部移动了这两行:

 require 'mocha/setup' require 'mocha/test_unit' 

我还删除了require 'test/unit' 。 看来mocha/test_unit已经为我做了。