NameError raised when using Mocha as a Rails plug-in
Reported by Chry Cheng | August 17th, 2009 @ 05:51 PM
I have the following set-up defined in my functional test
def setup @controller.expects(:logged_in?).returns(true) @controller.expects(:admin_user?).returns(true) end
Running the test generates the ff. error:
NameError: uninitialized constant Mocha::Mockery::ImpersonatingName /test/functional/xxxx_controller_test.rb:x:in `setup'
Before that, I see the ff. error at the top of the test log:
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.3/lib/active_support/test_case.rb:12: warning: already initialized constant Mocha
Now, according to http://selfamusementpark.com/blog/2009/07/30/rails233mochaconfusion/, Mocha requires the test framework to load before itself so it can set itself up correctly. Since init.rb in RAILS_ROOT/vendor/plugin/mocha runs before the test framework has been required, this will never be the case.
Current work-around is to comment out the line in init.rb that requires Mocha so that it can be required explicitly in the tests or helpers where the test framework is sure to have been loaded already.
However, a better and more permanent solution, if possible, is desired.
Comments and changes to this ticket
- State changed from new to open
Sorry for the delay in responding to this. I've just managed to reproduce it and am having a think about the best way to fix the problem.
Just so I'm clear, is there a particular reason you want to use Mocha as a plugin rather than a gem (vendorized or not)?
No particular reason. I'm somewhat new to Rails (a few months) and I just followed the directions in http://rubyforge.org/projects/mocha-rails/. I guess the comment is more on why it doesn't work as advertised. I'm OK with just updating the page to include the caveat/work around or to advise against installing it as a Rails plug-in.
Thanks. That's helpful.
The problem is because of the changes I made in 0.9.6 which mean that Mocha no longer loads the test frameworks (Test::Unit or MiniTest) itself, but expects you to load them before you load Mocha. Mocha will then monkey-patch whatever test frameworks you have loaded. I still think this was the right thing to do, because a number of people use Mocha without wanting either of the standard test frameworks being loaded.
However, when using Mocha as a Rails plugin, Mocha is loaded as a result of the environment being loaded in test_helper.rb. This is before Test::Unit is loaded. This means that Test::Unit does not get monkey-patched by Mocha and calls to Mocha methods fail as you have found.
I'm going to see if I can come up with a better solution. I'll let you know how I get on.
- State changed from open to resolved
- Tag changed from bug-report to bug-report, plugin
I've just released version 0.9.8 which does not load Mocha in the plugin. You will need to explicitly load Mocha after the test framework (as you have already done). I've also updated the documentation to reflect this.