I am using the default Rails tests.
In one test, I am overloading the Date.today method:
class Date
def self.today
Date.new(2011,7,19)
end
end
This works great for the tests in this file, but carries over to other tests and causes them to fail. How do I confine the effects of this code to a single file?
I gather that this may not be the best way to do tests. Are there any step by step tutorials that you recommend?
Thanks.
Rails 3.07
Thanks to d11wtq for the code above.
Here's how I did it:
$ gem install 'mocha'
Added gem 'mocha' to group :test in Gemfile (see below)
$ bundle install
In model_test.rb file, added require 'mocha' on line after require 'test_helper'
Added the following 3 lines to class ModelTest in model_test.rb:
setup do
Date.stubs(:today).returns(Date.new(2011, 7, 19))
end
I found this post a helpful introduction to Mocha: http://yarorb.wordpress.com/2007/11/26/mocks-and-stubs-in-ruby-on-rails-the-mocha-solution/
EDIT: More info:
I discovered that you need to add the following to remove the stub after each test. I put this after the setup method:
teardown do
Date.unstub(:today)
end
And, I think you need the following gem to the :test group in the Gemfile as well:
gem 'test-unit', '1.2.3'
Related
Question: Using Rails 5 & Minitest-Rails is there a way to default new Rails apps to default to Spec-style testing?
I teach TDD and it's annoying to have to have the students convert each time we make a new app.
You could create a template.rb file with following configuration:
gem_group :development, :test do
gem "rspec-rails"
end
after_bundle do
`rails g rspec:install`
end
And then build a new Rails project using the following command
rails new my_app -T -m /path/to/template.rb
It will build a new Rails application, add Rails RSpec gem to its Gemfile and execute the install step for RSpec.
Otherwise you could provide a pre-built Rails Git repository and build on top of that.
References:
Rails Application Templates — Ruby on Rails Guides
rspec/rspec-rails: RSpec for Rails-3+
Looks like you've already done the hard work of answering your question. Though if you're teaching a class with an opinionated group of test gems, and a modified test_helper.rb and a modified application.rb, you may wish to consider writing your own gem that your students can add to their Gemfile. The gem could have the test gems you want as dependencies, and then they can install everything else they need with something like:
bin/rails generate <gem_name>:install
Here's a gem I wrote that you can fork or modify or just use as inspiration.
https://github.com/schadenfred/testable
I actually stole your config code for the above gem, which you can see expressed in inside a generator that lives here:
lib/generators/installer/install_generator.rb
It looks like in config/application.rb you just have to add:
config.generators do |g|
g.test_framework :minitest, spec: true
end
However there's not an automatic way to make Minitest-Rails default to spec style testing.
I could go to rspec, but would rather stay with Minitest for the moment as we teach our students Minitest from the beginning.
Ok so #sonna had 90% of what I was looking for.
I ended up with help creating a .railsrc file with
-d postgresql
-m ~/.template.rb
And a template with:
# .template.rb
# Gems we've talked about in class, but which have absolutely nothing to do
# with setting up spec-style testing.
# Included here for convenience.
gem_group :development do
# Improve the error message you get in the browser
gem 'better_errors'
# Use pry for rails console
gem 'pry-rails'
end
# Add some extra minitest support
gem_group :test do
gem 'minitest-rails'
gem 'minitest-reporters'
end
# Add some code to some files to support spec-style testing
# For these injections, indentation matters!
inject_into_file 'config/application.rb', after: "class Application < Rails::Application\n" do
<<-'RUBY'
# Force new test files to be generated in the minitest-spec style
config.generators do |g|
g.test_framework :minitest, spec: true
end
RUBY
end
# Things to do after all the gems have been installed
after_bundle do
# Run rails generate minitest:install
generate "minitest:install", "--force"
# Add minitest reporters support. This must be run after
# rails generate minitest:install, because that command
# changes test/test_helper.rb
inject_into_file 'test/test_helper.rb', after: 'require "minitest/rails"' do
<<-'RUBY'
require "minitest/reporters" # for Colorized output
# For colorful output!
Minitest::Reporters.use!(
Minitest::Reporters::SpecReporter.new,
ENV,
Minitest.backtrace_filter
)
RUBY
end
end
This sets up my project with postgres for DB, and Minitest-rails using spec-style tests and includes minitest-reporters.
I have a rails 4 app. I have no tests at the moment, but when I created the app I didn't skip the default test unit so there are some empty test files (and other default settings) in my app.
Now I would like to use rspec + capybara, but don't know what the necessary extra steps are to properly install those and make sure the testing will work fine. I saw some answers on stackoverflow but thoose were pretty old.
As far as I know the installation looks like this if test unit is skipped on creation:
group :development, :test do
gem 'rspec-rails'
end
group :test do
gem 'capybara'
end
then
rails g rspec:install
Can sby tell me what the extra steps are?
Follow these steps:
add code to your_app/config/application.rb file:
config.generators do |g|
g.test_framework :rspec
end
add below code to your_app's Gemfile:
group :test, :development do
gem 'rspec-rails'
end
save it, and run bundle install to install rspec gem
Initialize the spec/ directory
rails generate rspec:install
Use the rspec command to run your specs:
bundle exec rspec
Hopefully it helps.
I want to use Coveralls.io for my gem Headhunter that I'm developing at the moment. The doc says, I should simply add
gem 'coveralls', require: false
to the project, but as far as I know, this isn't the right way to load gems within another gem. Instead, stuff like that should happen in the .gemspec file. So I tried to add it like this:
s.add_development_dependency('coveralls', '>= 2.0')
But this doesn't work - it breaks my gem's whole functionality:
$ rake
/Users/josh/.rvm/rubies/ruby-2.0.0-p353/bin/ruby -S rspec ./spec/headhunter/css_hunter_spec.rb ./spec/headhunter/css_validator_spec.rb ./spec/headhunter/html_validator_spec.rb
/Users/josh/Documents/Work/MuheimWebdesign/headhunter/lib/headhunter/css_validator.rb:6:in `<class:CssValidator>': undefined method `full_gem_path' for nil:NilClass (NoMethodError)
This is the file that breaks:
require 'net/http'
require 'nokogiri/xml'
module Headhunter
class CssValidator
VALIDATOR_PATH = Gem.loaded_specs['headhunter'].full_gem_path + '/lib/css-validator/'
So Gem.loaded_specs['headhunter'] isn't available anymore, no idea what's going on here.
What's wrong here?
I was wondering the same and I just got it working.
You need to add:
spec.add_development_dependency "coveralls", "0.7.0"
to your .gemspec (0.7.0 is the coveralls gem latest version as the time of writing this)
make sure to run bundle installsuccessfully
and add:
require 'coveralls'
Coveralls.wear!
to the beginning of your spec_helper.rb or test_helper.rb, before requiring anything else.
Hope this helps.
I am using rails console in the development environment and I want to use factories. How can I get access to them?
I have tried require "FactoryGirl" which returns
1.9.3p393 :301 > require "FactoryGirl"
LoadError: cannot load such file -- FactoryGirl
I do this the following way:
Start the rails console in test environment in sandbox mode.
rails console -e test --sandbox
You need this for two reasons:
Any changes you do are rolled back.
If you already have some seed data it might happen that the factories will start the serialization of attributes from 1, but these records might already exist.
Then in the console:
Require FactoryBot (was called FactoryGirl):
require 'factory_bot'
Load the factory definitions:
FactoryBot.find_definitions
Include the FactoryBot methods to avoid prefixing all calls to FB with FactoryBot (create instead of FactoryBot.create):
include FactoryBot::Syntax::Methods
P.S. For fabrication gem you can load the definitions in the rails console with:
Fabrication.manager.load_definitions
Also require 'faker' if you use it.
To solve this problem ensure that the factory bot gem is specifed in your Gemfile similar to this
group :development, :test do
gem 'factory_bot_rails'
end
Then bundle install.
This should make FactoryBot class available in the development console.
Hope this helps.
You need to require 'factory_bot_rails', which is the actual gem that's being used by Rails. That gem will include the Factory Bot library, making FactoryBot available.
You can either do this, or update your Gemfile to require it at startup as in muttonlamb's answer.
If you want to have it available each time you start the console, you can add this piece of code to the top of your config/environments/development.rb:
require 'factory_bot_rails'
require 'faker' # if you're also using faker gem
require 'rails/console/helpers'
Rails::ConsoleMethods.prepend(FactoryBot::Syntax::Methods)
Now you can use the built-in helpers right after starting the console, for example:
company = create(:company)
When running test/unit using the rake test command from the terminal within a rails 3 project directory, the test result output is not coloured. Hence, it cannot be interpreted at a glance.
Is there a way of getting colourised output for the results, as you can get in rspec?
>rspec --colour
I discovered that redgreen was abandoned years ago, and found this solution which works well and requires no script hacking. The output, however, shows which test is being run in real time. So it is a lot longer than built in test output. It does have nice colors.
http://rubygems.org/gems/turn
In my Gemfile:
group :test do
gem 'turn'
end
Then run:
$ bundle install
$ rake test
The gem 'turn' works great. The caveat is that it doesn't seem to work with Mocha, due to monkey-patching issues. If you are using Mocha, you can use the redgreen gem. See instructions above in the approved answer for this question.
Yes, you can use the redgreen gem. Include it in your gemfile:
group :development, :test do
gem 'redgreen'
end
And that's all you need for ruby 1.8. If you're using 1.9, there's a workaround. add the test-unit gem:
group :development, :test do
gem 'redgreen'
gem 'test-unit', '1.2.3
end
It's not perfect with 1.9 - test-unit seems to run an empty test suite after every rake task or generator call, which is harmless but annoying.
I am working on Rails 5.1 / minitest and I was also searching for a solution to make the reporting color. None of these test::unit solutions are working, so I googled and saw this solution. Just add the following:
# Gemfile
gem 'minitest-reporters'
# test/test_helper.rb
require "minitest/reporters"
Minitest::Reporters.use!
Github: minitest-reporters