Mocha Mock Carries To Another Test - ruby

I have been following the 15 TDD steps to create a Rails application guide - but have run into an issue I cannot seem to resolve. For the functional test of the WordsController, I have the following code:
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
In the Word class I have the following code:
class Word < ActiveRecord::Base
def self.random
all = Word.find :all
all[rand(all.size)]
end
end
When I run the tests, I experience the following error (shortened for brevity):
1) Failure: unexpected invocation: Word(...).random() satisfied expectations:
- expected exactly once, already invoked once: Word(...).random()
I have tried changing changing the order of the tests along with a multitude of other things, but time and time again I continue to receive the same test failure - that Word.random() has already been invoked.
I'm running Rails 3.0 beta 4 and Mocha 0.9.8. I've searched long and hard for a solution to my problem, but I can't seem to find it. I'm new to Ruby/Rails so am rather unfamiliar with the language and the frameworks.
Thanks in advance!

mocha needs to be loaded last. I struggled a lot with this problem too.
#Gemfile
group :test
gem 'mocha', '~>0.9.8', :require => false
...
end
and
test_helper.rb
....
#at the very bottom
require 'mocha'

I had the same problem, mocked functionality was not isolated to a test, it seems to be a problem with the load order of Mocha.
I had some issues getting Mocha to work with Rails3. I found a few stackoverflow posts regarding, but didn't stumble across the solution until I found a post on agoragames.com
Basically, in the Gemfile of your project, the require for Mocha should look like:
gem 'mocha', :require => false
Then in test/test_helper.rb, add a require line for mocha:
...
...
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'mocha'
class ActiveSupport::TestCase
...
...
I think the require line for mocha in the Gemfile means that you need to already have mocha installed as a gem, bundler won't take care of it for you.

How are you requiring mocha? Are you using bundler? It sounds a bit as if the mocha teardown hook isn't being called?

Additionally, it seems mocha_teardown is not being called with rails31. Mocks that are setup are never removed... (this additional hack fixes it)
class ActiveSupport::TestCase
def teardown
super
Mocha::Mockery.instance.teardown
Mocha::Mockery.reset_instance
end
end

Those solutions didn't work for me on their own, using Ruby 2.2.2, Rails 4.2.2, mocha 1.1.0, shoulda-context 1.2.1, factory_girl_rails 4.5.0 and a few more testing related gems.
What did it was also moving these two lines at the bottom of my test_helper.rb:
require 'mocha/setup'
require 'mocha/test_unit'
I also removed require 'test/unit'. It appears that mocha/test_unit already does that for me.

Related

Monkey Patching Mongoid models contained in a Ruby gem

I have a Ruby gem which gets used across multiple projects that contains some Mongoid models.
I'm currently trying to reuse them in a project and monkey patch some extra methods. However, when I require the project and run the tests. I get a NoMethodError. Any ideas where I'm going wrong?
Here's my main project file:
require 'bundler'
Bundler.require(:default)
require 'mongoid-elasticsearch'
Mongoid::Elasticsearch.prefix = ENV["MONGOID_ENVIRONMENT"]
require 'mongoid_address_models/require_all' # This is where I include my gem
Mongoid.load!(File.join(File.dirname(__FILE__), "..", "config", "mongoid.yml"), ENV["MONGOID_ENVIRONMENT"] || :development)
# Here are my monkey patched models
require 'models/street'
require 'models/locality'
require 'models/town'
require 'models/postcode'
require 'sorting_office/address'
module SortingOffice
end
And this is an example of one of the monkey patched models
class Postcode
REGEX = /([A-PR-UWYZ01][A-Z01]?[0-9IO][0-9A-HJKMNPR-YIO]\s?[0-9IO][ABD-HJLNPQ-Z10]{2})/i
def self.calculate(address)
postcode = UKPostcode.new(address.match(REGEX)[0])
where(name: postcode.norm).first
end
end
When I call Postcode.calculate(address) (for example), I get a NoMethodError
I think I've nailed this now. Rather than putting the monkey patch inside lib/models, I moved them to lib/sorting_office/models and required them like so:
require 'sorting_office/models/street'
require 'sorting_office/models/locality'
require 'sorting_office/models/town'
require 'sorting_office/models/postcode'
I'd still be interested to know WHY this worked though

How to quickly test Class behavior in ruby

I'm building a class-based Tic-tac-toe game with all the classes in tic_tac_toe.rb. I can load the class into irb for interactive testing with irb -r ./tic_tac_toe.rb, but I have to manually create a player and gameboard instance every time. I included p1 = Player.new int tic_tac_toe.rb but that does not seem to run.
More generally, is what I'm doing a good workflow or not? How should I go about writing some code for my class and testing it and going back? (Is there something simpler than unit testing for this small project?)
To directly address your question, you can simplify your workflow greatly with the addition of RSpec. RSpec is a BDD (behavior driven development) tool for Ruby that will let you describe your classes in an (arguably) more descriptive way than plain jane unit tests. I have included a small code sample below to help get you started.
Create a Gemfile if you do not have one for your project and add RSpec. If you've never done this check out Bundler for more information on Gemfiles.
# in your Gemfile
gem 'rspec' # rspec testing tool
gem 'require_relative' # allows you to require files with relative paths
Create a spec folder to house your specs (specs are what RSpec calls its tests).
# via Command Line (or in Windows Explorer) create a spec folder in your project
mkdir spec
Create a spec_helper.rb in the spec/ folder to house the configuration for your tests.
# in spec/spec_helper.rb
require "rspec" # require rspec testing tool
require_relative '../tic_tac_toe' # require the class to be tested
config.before(:suite) do
begin
#=> code here will run before your entire suite
#first_player = Player.new
#second_player = Player.new
ensure
end
end
Now that you've setup two players before your test suite runs, you can use these in your tests. Create a spec for your class that you would like to test and suffix it with _spec.
# in spec/player_spec.rb
require 'spec_helper' # require our setup file and rspec will setup our suite
describe Player do
before(:each) do
# runs before each test in this describe block
end
it "should have a name" do
# either of the bottom two will verify player's name is not nil, for example
#first_player.name.nil? == false
#first_player.name.should_not be_nil
end
end
Run these tests from the root of your project by using bundle exec rspec. This will look for a spec/ folder, load the spec helper, and run your specs. There is much more you can do with RSpec, such as work in Factories etc (this would be for larger projecxts). However for your project you would only need a few specs for your classes.
Other things I would suggest would be RSpec-Given, when you have a firm grasp of rspec. This gem helps DRY up your rspec tests and makes them a bit more readable.
You can also look into Guard and creating a Guardfile, which will watch your files for you and run tests when you change files.
Lastly, I included a small suggestion on a basic project structure to visualize this a bit easier.
/your_project
--- Gemfile
--- tic_tac_toe.rb
--- spec/
------- spec_helper.rb
------- player_spec.rb
I have linked all the referenced docs so if you have any questions definitely check the links out. The documentation on Bundler, RSpec, RSpec-Given, and Guard is pretty decent. Happy programming.

SimpleCov 0% coverage

I'm working on a small gem and included simplecov to spec_helper.rb two lines:
require 'simplecov'
SimpleCov.start
When I run the rspec test, the simplecov seems started correctly but the report is not:
Finished in 0.00214 seconds
8 examples, 0 failures
Coverage report generated for /home/......
spec to /home/megas/Work/calc/coverage. 0 / 0 LOC (0.0%) covered.
What might be a problem and how to fix it? Thanks
Also make sure to enable simplecov (a.k.a. SimpleCov.start) at the very beginning of your file; especially before you require your code.
I had the same symptoms. My problem was that in my test file:
#spec/oneclass_spec.rb
require 'oneclass'
require 'spec_helper'
...Rest of the test file
And I needed to change the order of the requires to:
#spec/oneclass_spec.rb
require 'spec_helper'
require 'oneclass'
...Rest of the test file
Hope this helps someone, I was going crazy...
I had a similar issue. For some reason, some modules were reported with 0% of coverage. After some investigation, I found that one of the initialisers required a controller, which caused modules to be loaded before Simplecov. What I did I moved Simplecov to initialiser:
# config/initializers/_coverage_rspec.rb
if Rails.env.test?
require 'simplecov'
SimpleCov.start 'rails'
end
If you're using spring, remember to turn it off when you run tests with coverage. In another case, the complete application code will be loaded before SimpleCov and report 0% coverage.
Just in case the above two answers didn't work (as in my case) a user on simplecov's github issues page suggested this, which worked for me.
Add this after you require simplecov-
module SimpleCov::Configuration
def clean_filters
#filters = []
end
end
SimpleCov.configure do
clean_filters
load_adapter 'test_frameworks'
end
If one of the above didn't work.
verify that in test.rb:
config.eager_load = false
In my case the issue was spring - I had to create a config/spring.rb with the following:
if ENV['RAILS_ENV'] == 'test'
require 'simplecov'
SimpleCov.start
end
as documented here.
I am running scripts from the command line and I found the solution was simply to put an exit at the end of my script. Doh!
Alternatively, the following also works
SimpleCov.at_exit do
SimpleCov.result.format!
end

How can fixtures be replaced with factories using rails3-generators?

I'm trying to replace fixture generation with factories using rails3-generators:
https://github.com/indirect/rails3-generators#readme
The gem is included in my Gemfile and has been installed:
# Gemfile
gem 'rails3-generators', :group => :development
I added the following to application.rb:
# application.rb
config.generators do |g|
g.stylesheets false
g.fixture_replacement :factory_girl
end
Yet 'rails g model Insect' is still generating fixtures ('insects.yml'). Is this working for others using Rails 3.0.4 and rails3-generators 0.17.4?
'rails g' shows the new generators available (such as Authlogic and Koala), but 'rails g model' still lists fixtures and doesn't refer to factories.
What else should I add to get this to work? Thanks.
Edit: I ran the gem's test suite, which includes a test for this, and it passes. No clue why it doesn't work with my app.
Edit2: I tried again with a test project and get the same result: fixtures instead of factories. If anybody could confirm whether this works for them with Rails 3.0.4 and rails3-generators 0.17.4, that would be helpful too because it would imply that I'm doing something wrong with my projects.
Edit3: It works if I run 'rails g model Insect -r factory_girl'. I thought the generator configuration in application.rb was supposed to take care of that, so this seems to be the source of the problem.
Searching around I found the following, which may help:
Try specifying a directory option for factory_girl's factories:
config.generators do |g|
g.stylesheets false
g.fixture_replacement :factory_girl, :dir => "spec/factories" # or test/factories, as the case may be
end
If you're using Test::Unit, try the following:
config.generators do |g|
g.stylesheets false
g.test_framework :test_unit, :fixture_replacement => :factory_girl
end
In both cases you will still need the rails3-generators gem, although there is a push to get that functionality into factory_girl_rails.
This Rails bug indicates that, at some point, the g.fixture_replacement code may not have worked right. Perhaps a test in 3.0.5 is in order. :)
A short update 9 years later:
instead of "factory_girl_rails" (which is deprecated now) use "factory_bot_rails".
Now, the factory gets created automagically:
$ rails g model tester name:string
Running via Spring preloader in process 31467
invoke active_record
create db/migrate/20200327152901_create_testers.rb
create app/models/tester.rb
invoke rspec
create spec/models/tester_spec.rb
invoke factory_bot
create spec/factories/testers.rb
I use rails 5.2.4, but this should also work with rails 6.

Testing a rake task in rspec (and cucumber)

I'm new to Ruby, and I've been trying to learn Rake, RSpec, and Cucumber. I found some code that will help me test my Rake tasks, but I'm having trouble getting it to work. I was told here: http://blog.codahale.com/2007/12/20/rake-vs-rspec-fight/ to drop this:
def describe_rake_task(task_name, filename, &block)
require "rake"
describe "Rake task #{task_name}" do
attr_reader :task
before(:all) do
#rake = Rake::Application.new
Rake.application = #rake
load filename
#task = Rake::Task[task_name]
end
after(:all) do
Rake.application = nil
end
def invoke!
for action in task.instance_eval { #actions }
instance_eval(&action)
end
end
instance_eval(&block)
end
end
into my spec_helper.rb file.
I've managed to take this code out and run it in my cucumber steps like this:
When /^I run the update_installers task$/ do
#rake = Rake::Application.new
Rake.application = #rake
load "lib/tasks/rakefile.rb"
#task = Rake::Task["update_installers"]
for action in #task.instance_eval { #actions }
instance_eval(&action)
end
instance_eval(&block)
Rake.application = nil
end
but when I try to get things working in rspec, I get the following error.
ArgumentError in 'Rake task
install_grapevine should install to
the mygrapevine directory'
wrong number of arguments (1 for 2)
/spec/spec_helper.rb: 21:in instance_eval'
/spec/spec_helper.rb: 21:inblock in invoke!'
/spec/spec_helper.rb: 20:in each'
/spec/spec_helper.rb: 20:ininvoke!'
/spec/tasks/rakefile_spec.rb:12:in `block (2 levels) in
'
Unfortunately, I've got just under a week of ruby under by belt, so the metaprogramming stuff is over my head. Could anyone point me in the right direction?
This works for me: (Rails3/ Ruby 1.9.2)
When /^the system does it's automated tasks$/ do
require "rake"
#rake = Rake::Application.new
Rake.application = #rake
Rake.application.rake_require "tasks/cron"
Rake::Task.define_task(:environment)
#rake['cron'].invoke
end
Substitute your rake task name here and also note that your require may be "lib/tasks/cron" if you don't have the lib folder in your load path.
I agree that you should only do minimal work in the Rake task and push the rest to models for ease of testing. That being said I think it's important to ensure that the code is ACTUALLY run in my cron tasks during my integration tests so I think very mild testing of the rake tasks is justified.
Since testing rake is just too much for me, I tend to move this problem around. Whenever I find myself with a long rake task that I want to test, I create a module/class in lib/ and move all the code from the task there. This leaves the task to a single line of Ruby code, that delegates to something more testable (class, module, you name it). The only thing that remains untested is whether the rake task invokes the right line of code (and passes the right parameters), but I think that is OK.
It might be useful to tell us which is the 21nd line of your spec_helper.rb. But given that the approach you posted digs deep in rake (referring to its instance variables), I would entirely abandon it for what I suggested in the previous paragraph.
I've just spent a little while getting cucumber to run a rake task so I thought I'd share my approach. Note: This is using Ruby 2.0.0 and Rake 10.0.4, but I don't think the behaviour has changed since previous versions.
There are two parts to this. The first is easy: with a properly set up instance of Rake::Application then we can access tasks on it by calling #[] (eg rake['data:import']). Once we have a task we can run it by calling #invoke and passing in the arguments (eg rake['data:import'].invoke('path/to/my/file.csv').
The second part is more awkward: properly setting up an instance of Rake::Application to work with. Once we've done require 'rake' we have access to the Rake module. It already has an application instance, available from Rake.application, but it's not yet set up — it doesn't know about any of our rake tasks. It does, however, know where to find our Rakefile, assuming we've used one of the standard file names: rakefile, Rakefile, rakefile.rb or Rakefile.rb.
To load the rakefile we just need to call #load_rakefile on the application, but before we can do that we need to call #handle_options. The call to #handle_options populates options.rakelib with a default value. If options.rakelib is not set then the #load_rakefile method will blow up, as it expects options.rakelib to be enumerable.
Here's the helper I've ended up with:
module RakeHelper
def run_rake_task(task_name, *args)
rake_application[task_name].invoke(*args)
end
def rake_application
require 'rake'
#rake_application ||= Rake.application.tap do |app|
app.handle_options
app.load_rakefile
end
end
end
World(RakeHelper)
Pop that code into a file in features/support/ and then just use run_rake_task in your steps, eg:
When /^I import data from a CSV$/ do
run_rake_task 'data:import', 'path/to/my/file.csv'
end
The behavior might have changed since the correct answer was posted. I was experiencing problems executing two scenarios that needed to run the same rake task (only one was being executed despite me using .execute instead of .invoke). I thought to share my approach to solve the issue (Rails 4.2.5 and Ruby 2.3.0).
I tagged all the scenarios that require rake with #rake and I defined a hook to setup rake only once.
# hooks.rb
Before('#rake') do |scenario|
unless $rake
require 'rake'
Rake.application.rake_require "tasks/daily_digest"
# and require other tasks
Rake::Task.define_task(:environment)
$rake = Rake::Task
end
end
(Using a global variable is suggested here: https://github.com/cucumber/cucumber/wiki/Hooks#running-a-before-hook-only-once)
In the step definition I simply called $rake
# step definition
Then(/^the daily digest task is run$/) do
$rake['collector:daily_digest'].execute
end
Any feedback is welcome.

Resources