I'm trying to add work to my guard/rspec testing and failed so far.
Gemfile:
group :development, :test do
gem 'rspec-rails', '2.14.1'
gem 'guard-rspec', '4.2.4'
gem 'guard-spork', '1.5.1'
...
end
spec_helper:
require 'rubygems'
require 'spork'
Spork.prefork do
unless ENV['DRB']
require 'simplecov'
SimpleCov.start 'rails'
end
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'factory_girl'
require 'database_cleaner'
require 'active_record/fixtures'
require 'capybara/rails'
require 'capybara/rspec'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f }
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.start
RSpec.configure do |config|
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/db/fixtures"
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
config.global_fixtures = [:character_attribute_type_categories, :character_attribute_types, :fund_types,
:professions, :financial_types, :activity_types, :legal_job_types, :menus, :menu_items, :weapon_type_categories,
:injury_types, :block_types]
config.infer_base_class_for_anonymous_controllers = false
config.backtrace_clean_patterns = [
/\/lib\d*\/ruby\//,
/bin\//,
/spec\/spec_helper\.rb/,
/lib\/rspec\/(core|expectations|matchers|mocks)/
]
config.include FactoryGirl::Syntax::Methods
end
require "mocha"
end
Spork.each_run do
if ENV['DRB']
require 'simplecov'
SimpleCov.start 'rails'
end
DatabaseCleaner.clean
Brothelking::Application.reload_routes!
end
Guardfile:
guard :spork, rspec_env: { 'RAILS_ENV' => 'test' }, cucumber: false, test_unit: false, rspec: true do
watch('config/application.rb')
watch('config/environment.rb')
watch(%r{^config/environments/.+\.rb$})
watch(%r{^config/initializers/.+\.rb$})
watch('Gemfile')
watch('Gemfile.lock')
watch('spec/spec_helper.rb') { :rspec }
watch(%r{^spec/factories/.+\.rb})
watch(%r{^spec/support/.+\.rb$})
watch('test/test_helper.rb') { :test_unit }
watch(%r{features/support/}) { :cucumber }
end
guard :rspec, cmd: "bundle exec rspec --color --format documentation --drb --backtrace", all_after_pass: false, all_on_start: true do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('spec/spec_helper.rb') { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
watch(%r{^app/views/(.+)/.*\.(erb|haml)$}) { |m| "spec/requests/#{m[1]}_spec.rb" }
end
guard 'jslint-on-rails' do
watch(%r{^app/assets/javascripts/.*\.js$})
watch('config/jslint.yml')
end
Now, when I run guard commenting out spork in the Guardfile, everything still works:
13:05:05 - INFO - Guard is using TerminalTitle to send notifications.
13:05:05 - INFO - Guard::RSpec is running
13:05:05 - INFO - Running all specs
No DRb server is running. Running in local process instead ...
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
DEPRECATION: RSpec::Core::Configuration#backtrace_clean_patterns is deprecated. Use RSpec::Core::Configuration#backtrace_exclusion_patterns instead. Called from /Users/xxx/Sites/xxx/spec/spec_helper.rb:88:in `block (2 levels) in <top (required)>'.
Run options: include {:focus=>true}
All examples were filtered out; ignoring {:focus=>true}
ActivitiesController
guest access
GET #index redirects to the login form
GET #show redirects to the login form
GET #new redirects to the login form
POST #create redirects to the login form
...
Calling it with spork activated doesn't:
13:00:52 - WARN - Guard::RSpec DEPRECATION WARNING: The :version option is deprecated. Only RSpec ~> 2.14 is now supported.
13:00:52 - INFO - Guard is using TerminalTitle to send notifications.
13:00:52 - INFO - Starting Spork for RSpec
Using RSpec
Preloading Rails environment
Loading Spork.prefork block...
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
DEPRECATION: RSpec::Core::Configuration#backtrace_clean_patterns is deprecated. Use RSpec::Core::Configuration#backtrace_exclusion_patterns instead. Called from /Users/xxx/Sites/xxx/spec/spec_helper.rb:88:in `block (2 levels) in <top (required)>'.
Spork is ready and listening on 8989!
13:01:02 - INFO - Spork server for RSpec successfully started
13:01:02 - INFO - Guard::RSpec is running
13:01:02 - INFO - Running all specs
Running tests with args ["--color", "--backtrace", "--failure-exit-code", "2", "--format", "documentation", "--format", "Guard::RSpec::Formatter", "--require", "/Users/xxx/.rvm/gems/ruby-1.9.3-p484#xxx/gems/guard-rspec-4.2.4/lib/guard/rspec/formatter.rb", "spec"]...
DEPRECATION: stub is deprecated. Use double instead. Called from /Users/xxx/Sites/xxx/spec/models/activity_report_spec.rb:22:in `block (2 levels) in <top (required)>'.
DEPRECATION: mock is deprecated. Use double instead. Called from /Users/xxx/Sites/xxx/spec/models/activity_report_spec.rb:65:in `block (2 levels) in <top (required)>'.
Done.
13:04:28 - INFO - Guard::JsLintOnRails started using config: /Users/xxx/Sites/xxx/config/jslint.yml
13:04:28 - INFO - Guard is now watching at '/Users/xxx/Sites/xxx'
Does anyone have an idea why this is not working?
Related
I'm testing for validation of entry of a city attribute in an addresses model. My model spec is as follows
require 'rails_helper'
RSpec.describe Address, :type => :model do
before(:each) do
#valid_attributes = {
street: 'rock avenue',
city: 'MSA',
zip: '00100',
person_id: 1
} # runs before each it block
end
context "Validations" do
it 'must have a city' do
a = Address.new
expect(a.errors_on(:city)).not_to be_empty
end
end
end
When I run the spec, i get the following error
1) Address Validations must have a city
Failure/Error: expect(a.errors_on(:city)).not_to be_empty
NoMethodError:
undefined method `errors_on' for #<Address:0xd844538>
# ./spec/models/address_spec.rb:19:in `block (3 levels) in <top (required)>'
My test gems are set up as following in my Gemfile
group :development, :test do
gem 'rspec-rails'
gem 'factory_girl_rails', :require => false
end
group :test do
gem 'capybara'
gem 'guard'
gem 'guard-rspec'
gem 'libnotify'
gem 'rspec-collection_matchers'
end
I have included the rspec collection matchers in my spec_helper, so I don't understand why I am getting this error
My spec_helper.rb
require 'capybara/rspec'
require 'factory_girl_rails'
require 'rspec/collection_matchers'
However I can see that the method, errors_on has been defined in rspec-collection_matchers gem as shown here
My .rspec
--color
--require spec_helper
I have also changed the position of
require 'rspec/collection_matchers'
to rails_helper.rb, but running the test suite again brings up the same error
rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'rspec/collection_matchers'
require 'capybara/rspec'
require 'factory_girl_rails'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include Capybara::DSL
config.include FactoryGirl::Syntax::Methods
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
My spec_helper.rb is empty with only the block below:
RSpec.configure do |config|
end
I am using Rails 4.1.0, rspec 3.0.0 and rspec-collection_matchers 1.0.0
Without seeing the repo, this is only a guess based on the information. I think this is a load order problem.
It looks like you are loading rspec/collection_matchers in spec_helper, not rails_helper. If you are using the new default configuration, --require spec_helper is in your .rspec file. When you run rspec this will require spec_helper very early on. When that happens it requires rspec/collection_matchers. However, at that point rails_helper has not been loaded. Unfortunately, this also means most of ActiveSupport including ActiveModel are not loaded yet. It also means the Rails autoloading functionality has not been loaded, so those won't get defined when you reference them.
All this to say, the check for ActiveModel here returns false. Which does not load errors_on.
Try moving the require into rails_helper.
Note on testing in isolation:
If you are going for faster testing in isolation this is my suggestion:
spec_helper should be kept very minimal and lightweight, that means for the most part you shouldn't add any require declarations to it
Move the requires you listed from spec_helper into rails_helper, those are mostly Rails specific and do not belong in spec_helper as Rails is not loaded there
If you need access to the other rspec/collection_matchers functionality in specs which do not require Rails, then just add the require 'rspec/collection_matchers' to the top of the spec file; Ruby will handle making sure it is only loaded once
I have recently tried installing Cucumber to supplement my testing environment. I already had Guard working with Spork and Rspec perfectly. I have set everything up so that it runs now, with Cucumber included, but two things are acting a bit funky.
First issue: when Guard runs the Cucumber tests, it pauses for about 10 seconds after printing "Disabling profiles..." After about 10 seconds, it runs the tests perfectly.
Second Issue: when I make changes to my features (which are stored in subdirectories, such as /features/users/sign_in.feature) or step definitions, guard doesn't run the tests. In order for me to run the tests, I have to manually hit and Guard proceeds to run all tests again. Clearly, that defeats the purpose of guard.
Here is some of my code:
Guard Terminal Output
ben#ben-K53SV:~/rails_projects/katmeer4$ bundle exec guard
16:51:57 - INFO - Guard is using Libnotify to send notifications.
16:51:57 - INFO - Guard is using TerminalTitle to send notifications.
16:51:57 - INFO - Guard::RSpec is running
16:51:57 - INFO - Running all specs
No DRb server is running. Running in local process instead ...
.....[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
........F....
Failures:
1) User abilities admin Index Page
Failure/Error: it {should have_selector('div', text: 'delete')}
Capybara::ExpectationNotMet:
expected to find css "div" with text "delete" but there were no matches
# ./spec/features/role_spec.rb:38:in `block (5 levels) in <top (required)>'
Finished in 1.18 seconds
18 examples, 1 failure
Failed examples:
rspec ./spec/features/role_spec.rb:38 # User abilities admin Index Page
Randomized with seed 16984
16:52:08 - INFO - Starting Spork for RSpec, Cucumber
Using RSpec, Rails
Using Cucumber, Rails
Preloading Rails environment
Preloading Rails environment
Loading Spork.prefork block...
Loading Spork.prefork block...
Spork is ready and listening on 8990!
Spork is ready and listening on 8989!
16:52:18 - INFO - Spork server for RSpec, Cucumber successfully started
16:52:18 - INFO - Running all features
Disabling profiles...
..
P-
(::) pending steps (::)
features/users/sign_in.feature:9:in `Then I see an invalid login message'
1 scenario (1 pending)
4 steps (1 skipped, 1 pending, 2 passed)
0m0.827s
Important Guardfile Code
guard 'spork', :cucumber_env => { 'RAILS_ENV' => 'test' },
:rspec_env => { 'RAILS_ENV' => 'test' } do
watch('config/application.rb')
watch('config/environment.rb')
watch('config/environments/test.rb')
watch(%r{^config/initializers/.+\.rb$})
watch('Gemfile')
watch('Gemfile.lock')
watch('spec/spec_helper.rb') { :rspec }
watch('test/test_helper.rb') { :test_unit }
watch(%r{features/support/}) { :cucumber }
end
guard 'cucumber' do
watch(%r{^features/.+\.feature$})
watch(%r{^features/support/.+$}) { 'features' }
watch(%r{^features/step_definitions/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'features' }
end
features/support/env.rb
require 'rubygems'
require 'spork'
Spork.prefork do
end
Spork.each_run do
end
require 'cucumber/rails'
ActionController::Base.allow_rescue = false
begin
DatabaseCleaner.strategy = :transaction
rescue NameError
raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end
Cucumber::Rails::Database.javascript_strategy = :truncation
You forgot to split the env.rb code into the prefork and each_run blocks. Try:
require 'rubygems'
require 'spork'
Spork.prefork do
require 'cucumber/rails'
end
Spork.each_run do
ActionController::Base.allow_rescue = false
begin
DatabaseCleaner.strategy = :transaction
rescue NameError
raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end
Cucumber::Rails::Database.javascript_strategy = :truncation
end
I have more than three guard gems in my Guardfile. When I run guard, I want a specific guard gem is to be disabled, without removing it from Guardfile. How should I disable it?
My next question is, rspec stops running test when it finds a first error. Is there any way to run all rspec errors at a time.
What are the guard gems are essential and easy to implement?
My Guardfile
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
guard 'migrate' do
watch(%r{^db/migrate/(\d+).+\.rb})
watch('db/seeds.rb')
end
guard :annotate do
watch( 'db/schema.rb' )
# Uncomment the following line if you also want to run annotate anytime
# a model file changes
watch( 'app/models/*.rb' )
# Uncomment the following line if you are running routes annotation
# with the ":routes => true" option
watch( 'config/routes.rb' )
end
guard :bundler do
watch('Gemfile')
# Uncomment next line if your Gemfile contains the `gemspec' command.
# watch(/^.+\.gemspec/)
end
guard :rspec do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
# Rails example
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml|\.slim)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
# Capybara features specs
watch(%r{^app/views/(.+)/.*\.(erb|haml|slim)$}) { |m| "spec/features/#{m[1]}_spec.rb" }
# Turnip features and steps
watch(%r{^spec/acceptance/(.+)\.feature$})
watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end
guard :rubocop do
watch(%r{.+\.rb$})
watch(%r{(?:.+/)?\.rubocop\.yml$}) { |m| File.dirname(m[0]) }
end
### Guard::Sidekiq
# available options:
# - :verbose
# - :queue (defaults to "default") can be an array
# - :concurrency (defaults to 1)
# - :timeout
# - :environment (corresponds to RAILS_ENV for the Sidekiq worker)
guard 'sidekiq', :environment => 'development' do
watch(%r{^workers/(.+)\.rb$})
end
guard 'rails' do
watch('Gemfile.lock')
watch(%r{^(config|lib)/.*})
end
# Sample guardfile block for Guard::Haml
# You can use some options to change guard-haml configuration
# output: 'public' set output directory for compiled files
# input: 'src' set input directory with haml files
# run_at_start: true compile files when guard starts
# notifications: true send notifictions to Growl/libnotify/Notifu
# haml_options: { ugly: true } pass options to the Haml engine
guard 'puma' do
watch('Gemfile.lock')
watch(%r{^config|lib|api/.*})
end
guard 'rake', :task => 'build' do
watch(%r{^my_file.rb})
end
Group your Guard plugins into groups. This allows you to select a specific group from the command line or switch them at runtime using the scope interactor command.
guys.
Rails 3.2.12
I have a sample test spec/models/user_spec.rb
require 'spec_helper'
describe User do
pending "add some examples to (or delete) #{__FILE__}"
end
spec/spec_helper.rb
require 'spork'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../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.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.color_enabled = true
config.tty = true
config.formatter = :documentation # :progress, :html, :textmate
end
end
Spork.each_run do
end
When I run the test without Spork I get:
$ rspec
c:/ruby/Ruby193/lib/ruby/gems/1.9.1/gems/activesupport-3.2.12/lib/active_support
/dependencies.rb:251:in `block in require': iconv will be deprecated in the futu
re, use String#encode instead.
User
add some examples to (or delete) d:/sites/efiling/spec/models/user_spec.rb (PE
NDING: No reason given)
Pending:
User add some examples to (or delete) d:/sites/efiling/spec/models/user_spec.r
b
# No reason given
# ./spec/models/user_spec.rb:4
Finished in 0.31249 seconds
1 example, 0 failures, 1 pending
Randomized with seed 10437
When I run the test with Spork I get:
$ rspec . --drb
<-- Slave(1) run done!
In Spork window:
Loading Spork.prefork block...
--> DRb magazine_slave_service: 1 provided...
Running tests with args ["--color", "."]...
<-- take tuple(1); slave.run...
-- (1);run done
Done.
-- build slave 1...
Preloading Rails environment
Why does Rspec give no info about pending, failed etc tests when I use it with Spork?
I found an answer to your question: How can I configure rspec to show output with spork?
For your convenience, the way posted to circumvent this error is to add this to the Spork.each_run block:
if Spork.using_spork?
RSpec.configure do |config|
config.reset
config.output_stream = $stdout
end
end
I had the same problems as you, and once I added this in, I was getting normal output again.
I don't know why libnotify stoped showing informations about finished tests.
It shows Spork message: "Rspec successfully started." But after that does not show anything. I`m using Ubuntu.
guard 'spork', :cucumber => false, :rspec_env => { 'RAILS_ENV' => 'test' } do
watch('config/application.rb')
watch('config/environment.rb')
watch(%r{^config/environments/.+\.rb$})
watch(%r{^config/initializers/.+\.rb$})
watch('spec/spec_helper.rb')
watch(%r{^spec/support/.+\.rb$})
end
guard 'rspec', :version => 2, :cli => "--drb", :all_on_start => false, :all_after_pass => false do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
watch('spec/acceptance/acceptance_helper.rb') { "spec" }
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
# Capybara request specs
watch(%r{^app/views/(.+)/.*\.(erb|haml)$}) { |m| "spec/requests/#{m[1]}_spec.rb" }
# watch(%r{^spec/support/(requests|controllers|mailers|models)_helpers\.rb}) { |m| "spec/#{m[1]}" }
# watch(%r{^app/controllers/(.+)_(controller)\.rb}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/requests/#{m[1]}_spec.rb"] }
watch(%r{^app/(.+)\.rb}) { |m| "spec/#{m[1]}_spec.rb" }
end
My spec_helper: ***
When I initialize guard:
Running tests with args ["--color", "--format", "progress", "--format", "Guard::RSpec::Formatter::NotificationRSpec", "--out", "/dev/null", "--require", "/home/rege/.rvm/gems/ruby-1.9.2-p290/gems/guard-rspec-0.5.10/lib/guard/rspec/formatters/notification_rspec.rb", "spec"]...
How to diagnose where is the problem?
EDIT:
Solution: https://github.com/guard/guard-rspec/issues/90#issuecomment-3435651
I had this problem as well and installed the guard-spork (https://github.com/guard/guard-spork) gem (added it to my rails Gemfile and bundle installed). Then, per the instructions on that page, I ran 'guard init spork' which adds a 'spork' section to your Guardfile for files you can watch.
When i ran bundle exec guard, it actually makes sure spork is also started and presto! my test file changes were getting run and the results posted to the notifier. For the record, I use Ubuntu 11.10 64bit with ruby rvm. The relevant gems in my Gemfile were gem 'guard-rspec', gem 'guard-spork', gem 'rspec-rails', gem 'watchr', gem 'spork', gem 'libnotify'. Not sure if all are relevant.
You can find the step by step I used for this in Hartl's awesome Rails tutorial http://ruby.railstutorial.org/chapters/static-pages#sec:guard (sections 3.6.2 and 3.6.3).