Cucumber prevent from clearing database - ruby-on-rails

due to a heavy growing project I'm running into the trouble that the database rebuild process of cucumber really takes a long time.
Since it is a application where the actual content of the table doesn't matter, I'd like to skip the rebuild process.
Unfortunately wether cucumber nor database_cleaner seem to support this, doesn't they?
My cucumber env settings may be found below
Thanks and many regards,
Joe
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'capybara/rails'
require 'capybara/cucumber'
require 'capybara/session'
require 'cucumber/rails/capybara_javascript_emulation'
Capybara.default_selector = :css
ActionController::Base.allow_rescue = false
Cucumber::Rails::World.use_transactional_fixtures = false
Capybara.default_driver = :selenium
if defined?(ActiveRecord::Base)
begin
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
rescue LoadError => ignore_if_database_cleaner_not_present
end
end

An easy way to stop database_cleaner from cleaning one of your tables is to configure it like this:
DatabaseCleaner.strategy = :truncation, {:except => %w[states]}
In this example, once the table states is loaded with information, it doesn't clean it.

Related

coverband gem for my application

Am trying to work on coverband gem that will show the code covered in my application. I followed commands from this link https://github.com/danmayer/coverband, and used "rake test" to generate coverage. Added
require 'simplecov'
SimpleCov.start
to test/test_helper.rb and config/application.rb as in simplecov gem documentation. My question is how to get output for the entire clicks and adds that i do on my application? For now i end up with output on initializers and configs but i need codes covered for controllers, models and views.
Would somebody help with this ?
Hey I am the author of Coverband. I wanted to help make sure people understand that Coverband isn't for test code coverage. For that you should just look at Simplecov which has all you need. Coverband, provides runtime code coverage, which is useful for seeing what code is executed on production servers. This helps find features and code that is being maintained but isn't in use by any actual users. The use case from Simplecov is very different. Coverband uses the Simplecov output formatters, but besides that they don't share other code or the same goals.
Hope that helps.
I managed to get a working spec/spec_helper.rb configuration that executes SimpleCov correctly simply using the $ rspec spec/ command thanks to a comment on the Github issue that sent me to this blog entry, and its example spec/spec_helper.rb. All reasons why this works are contained in the (very detailed!) blog entry. Replace SampleApp with the name of your application
Spork.prefork do
unless ENV['DRB']
require 'simplecov'
SimpleCov.start 'rails'
end
require 'rails/application'
require Rails.root.join("config/application")
ENV["RAILS_ENV"] ||= 'test'
require 'rspec/rails'
require 'rspec/autorun'
RSpec.configure do |config|
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false
config.before :each do
if Capybara.current_driver == :rack_test
DatabaseCleaner.strategy = :transaction
else
DatabaseCleaner.strategy = :truncation
end
DatabaseCleaner.start
end
config.after do
DatabaseCleaner.clean
end
config.infer_base_class_for_anonymous_controllers = false
end
end
You might try using Cucumber with a Web driver. That should get clicks in the coverage report. If you need Javascript evaluation, you'll want to use Selenium.

Spork & Rails 3.1 engine: helpers are not reloaded

I'm developing a Rails 3.1 engine and want to test it. I use RSpec for this, and everything works nicely, but when trying to use Spork, I have the problem that my helpers are not correctly reloaded.
I read a lot about a similar problem with models, and I came up with the following possible fix:
# my_engine/spec/spec_helper.rb
ActiveSupport::Dependencies.clear
ActiveRecord::Base.instantiate_observers
Dir[File.join(File.dirname(__FILE__), '..', 'app', 'helpers', '*.rb')].each do |file|
require file
end
# my_engine/spec/dummy/config/environments/test.rb
Dummy::Application.configure do
# ...
config.cache_classes = !(ENV['DRB'] == 'true') # Ensure that classes aren't cached when using Spork.
# ...
end
This works as far as it definitely is reloading ever helper file (I added a breakpoint to check this), but the changes are not reflected within the tests, only a restart of Spork does. Maybe it's because helpers are modules, and the tests don't rely on the module but on the classes that implement the modules, so the modules are properly reloaded but not properly mixed in??
At the time being, I'm just putting all intitializer code into the each_run block:
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
I have done a lot of research about this topic, and I've written about in these two blog posts:
How to Develop Rails 3.1 Engines with Ease: Part I – The engine
How to Develop Rails 3.1 Engines with Ease: Part II – The gem
Regarding especially to my question above: I can imagine that it didn't work because I didn't require 'rspec/autorun' in the Spork.prefork block, but I'm not completely sure.
Here's the spec_helper.rb for my current engine (which successfully reloads everything as needed):
require 'rubygems'
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.use_transactional_fixtures = true
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.infer_base_class_for_anonymous_controllers = false
config.treat_symbols_as_metadata_keys_with_true_values = true
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
end
Spork.each_run do
# This code will be run each time you run your specs.
end

Spork doesn't reload code

I am using following gems and ruby-1.9.3-p194:
rails 3.2.3
rspec-rails 2.9.0
spork 1.0.0rc2
guard-spork 0.6.1
Full list of used gems is available in this Gemfile.lock or Gemfile.
And I am using this configuration files:
Guardfile
.rspec
spec_helper.rb
factories.rb
If I modify any model (or custom validator in app/validators etc) reloading code doesnt works.
I mean when I run specs (hit Enter on guard console) Spork contain "old code" and I got obsolete error messages. But when I manually restart Guard and Spork (CTRC-C CTRL-d guard) everything works fine. But it is getting tired after few times.
Questions:
Can somebody look at my config files please and fix error which block updating code.
Or maybe this is an issue of newest Rails version?
PS This problem repeats and repeats over some projects (and on some NOT). But I haven't figured out yet why this is happens.
PS2 Perhaps this problem is something to do with ActiveAdmin? When I change file in app/admin code is reloaded.
Workaround:
# config/environments/test.rb
config.cache_classes = false
But it is "double-edged sword".
Specs run now ~2.0x time longer. But it is still faster than restarting again and again Spork.
Update 28.06.2013
Use Zeus. It works perfectly. Benchmarks are at the bottom..
If you are using 1.9.3 consider installing special patches which REALLY speed up loading app.
RVM patchsets
rbenv instructions
Background & Benchmark:
I have a quite large 1.9.3 app and I wanted to speedup app loading, Spork doesn't work so I started looking for other solutions:
I write a empty spec to see how long it takes to load my app
-/spec/empty_spec.rb
require 'spec_helper'
describe 'Empty' do
end
plain 1.9.3
time rspec spec/empty_spec.rb 64,65s user 2,16s system 98% cpu 1:07,55 total
1.9.3 + rvm patchsets
time rspec spec/empty_spec.rb 17,34s user 2,58s system 99% cpu 20,047 total
1.9.3 + rvm patchsets + zeus
time zeus test spec/empty_spec.rb 0,57s user 0,02s system 58% cpu 1,010 total
[w00t w00t!]
Alternatively, you can add guards for your models, controllers and other code. It'll make guard reload spork when any of these files change.
guard 'spork',
:rspec_env => {'RAILS_ENV' => 'test'} do
watch(%r{^app/models/(.+)\.rb$})
watch(%r{^lib/(.+)\.rb$})
end
I had the same problem. Tests were reloaded and ran successfully for changes to model_spec.rb. When I made changes to the model.rb file the tests were re-run, however the code seemed to be cached - so the changed were not applied.
It required a combination of a few answers to get things working:
# /config/environments/test.rb
config.cache_classes = !(ENV['DRB'] == 'true')
# spec_helper.rb
Spork.each_run do
.....
ActiveSupport::Dependencies.clear
end
I also updated spork to (1.0.0rc3) and replaced the spork gem with spork-rails, as mentioned by #23inhouse above. However, I did not see any difference between either gem in the gemfile although upgrading spork may have had an effect.
Hopefully this helps someone else not spend any more hours banging their head against the wall.
Great as Spork is, it seems to break on every Rails upgrade :(
On Rails, 3.2.3, I've added this snippet in spec/spec_helper.rb to forcibly reload all ruby files in the app directory.
Spork.each_run do
# This code will be run each time you run your specs.
Dir[Rails.root + "app/**/*.rb"].each do |file|
load file
end
end
In my case the problem was draper. It didn't allow spork to reload the models.
Spork.prefork do
ENV['RAILS_ENV'] ||= 'test'
# Routes and app/ classes reload
require 'rails/application'
Spork.trap_method(Rails::Application::RoutesReloader, :reload!)
Spork.trap_method(Rails::Application, :eager_load!)
# Draper preload of models
require 'draper'
Spork.trap_class_method(Draper::System, :load_app_local_decorators)
# Load railties
require File.expand_path('../../config/environment', __FILE__)
Rails.application.railties.all { |r| r.eager_load! }
...
Just remember to insert the trap method for Draper before loading the environment.
Spork got cleaned up and some functionality was extraced.
https://github.com/sporkrb/spork-rails
add this to your Gemfile
gem 'spork-rails'
Fixed the same problem by adding more to the spork.each_run method.
Rails 3.2.2
Also, I recommend running one test a time. It's much faster, less noisy, and we normally work on one test at a time anyway.
rspec spec -e 'shows answer text'
I find it is faster and easier than using Guard because I was just sitting around waiting for Guard to finish. Also, Guard did not always reload the right files and run the right tests when I made a change.
spec_helper.rb file:
require 'spork'
Spork.prefork do
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
require 'capybara/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
end
Spork.each_run do
Dir[Rails.root.join('spec/support/**/*.rb')].each {|f| require f}
RSpec.configure do |config|
# 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
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
config.include RequestHelpers, :type => :request
config.before :suite do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with :truncation
end
config.before :each do
DatabaseCleaner.start
end
config.after :each do
DatabaseCleaner.clean
end
config.include(MailerHelpers)
config.before(:each) { reset_email }
end
# This code will be run each time you run your specs.
end

RSpec - shared DB conn. & transactional fixtures not working

I tried to follow José Valim's advice on faster test suites, but to no avail.
I use Spork and put the AR monkey patch in the Spork.each_run block (see the spec helper below).
However, my request specs fail because the database is not cleaned between runs - specifically, I get errors such as expected 1 record, got X when doing assertions like Model.should have(1).record.
Update
The problem lies with request specs using Javascript. See the following spec - it fails when I use js: true, but not if I remove that (I use RSpec's config.treat_symbols_as_metadata_keys_with_true_values = true, fwiw.)
# encoding: UTF-8
require 'spec_helper'
feature "Create a shift", :js do
scenario %q(
In order to plan the workload
As a coordinator
I want to schedule shifts
And I want to see when they're scheduled for
) do
visit shifts_path
click_link "new_shift_#{Date.current}"
fill_in 'shift_note', with: 'Casper - luk'
click_link_or_button 'submit'
Shift.should have(1).record
Shift.last.begins_at.should == Date.current
page.should have_selector("ol[data-date=\"#{Date.current}\"] li#shift_#{Shift.last.id}")
end
end
I can tell it's related to the DB not being cleaned, because it fails the first time (expected 1 record, got 0), passes the second time (because there's 1 record in the DB) and then fails again on any subsequent runs (expected 1 record, got 2 etc.)
I'm trying to avoid using a gem like DatabaseCleaner, to keep dependencies as few as possible, and to avoid a speed decrease in the test suite.
Any help/info/pointers are greatly appreciated!
Relevant info:
Rails 3.2.2
RSpec 2.9.0
Capybara 1.1.2
Capybara-webkit 0.11.0
FactoryGirl 2.6.4
Spork 0.9.0
Guard 1.0.1
Guard-spork 0.5.2
on a Macbook Air, OS X 10.7.3 (if that's relevant)
And my spec helper:
# encoding: UTF-8
require 'rubygems'
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.use_transactional_fixtures = true
config.treat_symbols_as_metadata_keys_with_true_values = true
config.infer_base_class_for_anonymous_controllers = false
config.include Factory::Syntax::Methods
Capybara.javascript_driver = :webkit
Rails.logger.level = 4 # speed - http://blog.plataformatec.com.br/tag/capybara/
end
end
Spork.each_run do
require 'factory_girl_rails'
class ActiveRecord::Base
mattr_accessor :shared_connection
##shared_connection = nil
def self.connection
##shared_connection || retrieve_connection
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
end
After much investigating, the problem seems to be with specs using JS in general, and not really the AR monkey patch.
I've re-phrased the problem in a new question here: RSpec+Capybara request specs w/ JS not working

Can't get rspec, spork and debugger to play nice

Given I am a dumb programmer
and I am using rspec
and I am using spork
and I want to debug ...mmm...let's saaay, a spec for Phone.
Then, where should I put the "require 'ruby-debug'" line in order to halt processing at a particular point in the phone_spec.rb? (All I'm asking for is a big fat arrow that even a challenged programmer could see :-3 )
I've tried many locations, and unless I didn't test them correctly, there's something weird going on:
In spec_helper.rb at the following locations:
require 'rubygems'
require 'spork'
<= TRIED IT HERE
ENV["RAILS_ENV"] ||= 'test'
Spork.prefork do
require File.dirname(__FILE__) + "/../config/environment" #unless defined?(RAILS_ROOT)
require 'spec/autorun'
require 'spec/rails'
require 'machinist/active_record'
require 'faker'
require 'sham'
<= TRIED IT HERE
end
Spork.each_run do
require File.expand_path(File.dirname(__FILE__) + "/blueprints")
<= TRIED IT HERE
end
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}
Spec::Runner.configure do |config|
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
config.before(:all) { Sham.reset(:before_all) }
config.before(:each) { Sham.reset(:before_each) }
<= TRIED IT HERE
end
I'm running Spork and Autospec with ruby-debug. Later versions of Spork have an external ruby-debug library you can require, it's experimental so use at your own risk. In my prefork block I just have :
require 'spork/ext/ruby-debug'
It'll break out to a debug session in the terminal you have Spork running. There are methods etc to initiate remote connection setup and so on, and recent commits have had updates and fixes applied to their debugging functionality so it's under active development. Hopefully it'll be core and tested soon ...
I've always put it in config/environments/test.rb and the put the debugger at the breakpoint in my app code (as opposed to the spec).

Resources