Suddenly, every test in our Rails 4 app fails - ruby-on-rails-4

My co-workers tell me these tests pass when they run them. But I just checked the code out from Bitbucket, and for me, the tests fail. I made sure that my machine has the same version as my co-workers:
Rails 4.2.4
Ruby 2.2.3
rake, version 10.4.2
After some pain with nokogiri, I was able to get "bundle install" to run.
But if I do this:
bin/rake test
Every test fails:
27 runs, 0 assertions, 0 failures, 27 errors, 0 skips
with an error that looks like this:
6) Error:
ProfilesControllerTest#test_#update:
NoMethodError: undefined method `type' for nil:NilClass
Error:
ProfilesControllerTest#test_#update:
NoMethodError: undefined method `each' for nil:NilClass
Here is an example of some failing code:
require 'test_helper'
class ProfilesControllerTest < ActionController::TestCase
test '#update' do
profile = profiles(:no_address_profile)
login(profile)
VCR.use_cassette('essex_street_ny') do
patch :update, profile: {address: '15 Essex street, New York, NY, USA', zipcode: '10002'}
end
updated_profile = Profile.find_by_user_id(profile.user_id)
assert_equal '15 Essex street, New York, NY, USA', updated_profile.address
assert_equal '10002', updated_profile.zipcode
assert_redirected_to root_path
end
test '#update with only zipcode' do
profile = profiles(:no_address_profile)
login(profile)
VCR.use_cassette('only_10002_zipcode') do
patch :update, profile: {zipcode: '10002'}
end
updated_profile = Profile.find_by_user_id(profile.user_id)
assert_equal '10002', updated_profile.zipcode
assert_redirected_to root_path
end
def login(profile)
session[:user_id] = profile.user_id
end
end
So what is really happening here?
UPDATE:
If I do :
rake db:fixtures:load
I get:
rake aborted!
NoMethodError: undefined method `type' for nil:NilClass

It sounds like you need to run migrations in your test environment. You can do that like so:
rake db:migrate RAILS_ENV=test

Related

Capybara::Poltergeist Status error, failed to reach server

I am trying to make some tests with Rspec/Capybara/Poltergeist on my Rails 4 application, Phantomjs is installed (version 2.2.1), but I always get this error :
Failure/Error: visit(perfect_landing_page_path)
Capybara::Poltergeist::StatusFailError:
Request to 'http://127.0.0.1:49623/path' failed to reach server, check DNS
and/or server status
The test i'm working on :
require 'rails_helper'
RSpec.feature 'Subscription', :type => :feature do
let!(:plan) { create(:plan) }
let!(:landing_page) { create(:landing_page) }
before(:each) { landing_page.default_plan = plan }
describe 'landing_page#perfect_show' do
scenario 'form display', js: true do
plan_2 = create(:plan)
plan_3 = create(:plan)
landing_page.plans << plan_2
landing_page.plans << plan_3
visit(perfect_landing_page_path)
expect(page).to have_css(".start-now", count: 3)
first(".start-now").click
expect(page).to have_css("#new_user")
end
end
end
My Gemfile looks like this :
gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
gem 'guard-rspec'
group :test do
gem 'database_cleaner'
gem 'capybara'
gem 'capybara-screenshot'
gem 'poltergeist'
gem 'selenium-webdriver'
gem 'shoulda-matchers', require: false
gem 'show_me_the_cookies'
end
My spec/support/capybara.rb file :
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'
require "capybara/poltergeist" # Add this line to require poltergeist
require 'selenium-webdriver'
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, {:js_errors => false, :default_max_wait_time => 30, :timeout => 30, phantomjs_options: [
'--load-images=no',
'--ignore-ssl-errors=true',
'--ssl-protocol=any']})
end
Capybara.register_driver :poltergeist_debug do |app|
Capybara::Poltergeist::Driver.new(app, :inspector => true)
end
Capybara.configure do |config|
config.javascript_driver = :poltergeist
config.ignore_hidden_elements = true
config.default_max_wait_time = 30
end
My spec_helper.rb file :
require 'capybara/rspec'
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
Did someone encounter this problem before ? Does anyone have a solution for this ? I have been banging my head for days looking on the web...
Thank you very much.
PS : it works fine on my friend's mac (Yosemite or El Capitan), just not on mine.
I was having this problem in CI (CodeShip).
Adding a call to bundle exec rake assets:precompile at the end of the setup commands seemed to fix it:
CodeShip CI Setup Commands:
rvm use 2.3.4 --install
bundle install
export RAILS_ENV=test
bundle exec rake db:schema:load
bundle exec rake assets:precompile
Also had a whitelist per #agbodike but in the rails_helper.rb
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
I had the same issue and it was due to a 3rd party script timing out. You can prevent loading of 3rd party scripts with a blacklist. For example:
config.before(:each, js: true) do
page.driver.browser.url_blacklist = ["http://use.typekit.net"]
end
would prevent any URL starting with http://use.typekit.net from being called for each test that uses the js driver. More information can be found at:
https://robots.thoughtbot.com/speed-up-javascript-capybara-specs-by-blacklisting-urls
Alternatively you can use a whitelist:
config.before(:each, js: true) do
page.driver.browser.url_whitelist = ["127.0.0.1"]
end
which will block all requests not to 127.0.0.1
I placed the configuration in spec/feature_helper.rb to ensure it was only set for feature specs.
You can avoid these by precompile the assets before tests.
And the code is:
RSpec.configure do |config|
config.before :all do
ENV['PRECOMPILE_ASSETS'] ||= begin
case self.class.metadata[:type]
when :feature, :view
STDOUT.write "Precompiling assets..."
require 'rake'
Rails.application.load_tasks
Rake::Task['assets:precompile'].invoke
STDOUT.puts " done."
Time.now.to_s
end
end
end
end
more info

Rails 4 ActiveJobs using different enqueue adapter and having NoMethodError

I am trying to run an ActiveJob job from a controller method, but it fails and I can't spot the right place of the issue:
#app/controllers/users_controller.rb
1 class UsersController < ApplicationController
2 def new
3 #user = User.new
4 end1
5
6 def create
7 #user = User.create(user_params)
8 PoliciesChecksJob.new(#user.id).enqueue
9 # redirect to somewhere
10 end1
11 end
#app/jobs/policies_checks_job.rb
class PoliciesChecksJob < ActiveJob::Base
queue_as :default
def perform(user_id)
SearchPoliciesCommands.new.execute(user_id)
end
end
Logs summary:
Started POST "/users" for ::1 at 2015-03-30 15:01:03 +0100
Processing by UsersController#create as HTML
...(params)
(0.1ms) BEGIN
... (inserts the user)
(0.3ms) COMMIT
[ActiveJob] Enqueued PoliciesChecksJob (Job ID: da...e2) to Sneakers(default) with arguments: 1
Completed 500 Internal Server Error in 76ms
NoMethodError (private method `warn' called for nil:NilClass):
app/controllers/users_controller.rb:8:in `create'
I'd appreciate any thought.
Basically there was a little problem with the enqueue adapter:
I prefer to use Sneakers due the fact that it does work fine with RabbitMQ.
So I had to specify that I want a different enqueue adapter than the default one:
#config/application.rb
config.active_job.queue_adapter = :sneakers
Install RabbitMQ, and start it:
(preferible in a different terminal tab)
$ rabbitmq-server
Install the gem sneakers and run its deamon in (preferible other terminal tab):
$ sneakers work ActiveJob::QueueAdapters::SneakersAdapter::JobWrapper
--require app/jobs/policies_checks_job.rb

Why I get undefined method each_key?

When I try to deploy my app, I get this error:
rake aborted!
NoMethodError: undefined method each_key' for false:FalseClass /var/deploy/dcaclab/web_head/shared/bundle/ruby/2.2.0/gems/tinymce-rails-4.1.6/lib/tinymce/rails/asset_manifest.rb:41:ineach'
/var/deploy/dcaclab/web_head/shared/bundle/ruby/2.2.0/gems/tinymce-rails-4.1.6/lib/tinymce/rails/asset_installer.rb:26:in cleanup_assets' /var/deploy/dcaclab/web_head/shared/bundle/ruby/2.2.0/gems/tinymce-rails-4.1.6/lib/tinymce/rails/asset_installer.rb:13:ininstall'
/var/deploy/dcaclab/web_head/shared/bundle/ruby/2.2.0/gems/tinymce-rails-4.1.6/lib/tasks/tinymce-assets.rake:12:in `block in '
Tasks: TOP => assets:precompile
Can someone help?
First please check your production.rb file under config/environments
Set these line there
config.serve_static_assets = true
config.assets.compile = false
Then run this command to compile your assets for production
rake assets:precompile RAILS_ENV=production
However if you wish to include tinymce-jquery.js independently, you will need to add it to the precompile list in config/environments/production.rb:
config.assets.precompile << "tinymce-jquery.js"

Rails 4.1, Guard 2.10, and Minitest 5.4.1 -- RuntimeError & Rails::Generators::TestCase

I'm trying to set up Guard with Minitest in a new Rails 4 project. I updated my Gemfile with the following:
group :development do
gem 'guard'
gem 'guard-minitest'
end
And then ran bundle exec guard init minitest.
I've got a pretty simple test like so:
require 'test_helper'
describe ClassToBeTested do
describe "#initialize" do
it "should return a ClassToBeTested object" do
obj = ClassToBeTested.new
obj.must_be_kind_of ClassToBeTested
end
end
end
The class being tested is in app/services/class_to_be_tested.rb.
When I run bundle exec guard -n f I get the following:
11:35:43 - INFO - Guard::Minitest 2.3.2 is running, with Minitest::Unit 5.4.1!
11:35:43 - INFO - Running: all tests
Run options: --seed 36837
# Running:
E
Finished in 0.005190s, 192.6728 runs/s, 0.0000 assertions/s.
1) Error:
ClassToBeTested::#initialize#test_0001_should return a ClassToBeTested object:
RuntimeError: You need to configure your Rails::Generators::TestCase destination root.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
11:35:45 - INFO - Guard is now watching at '/home/sean/Code/Ruby/work/project'
Is there something I'm missing? Something in Guard/Minitest/Rails that needs to be configured to work properly?
Figured it out -- apparently it thought that the class was a generator. Adding the following line to test_helper.rb inside the class TestCase block fixed the issue:
register_spec_type(/ClassToBeTested/, Minitest::Spec)
Is there a way to have all the classes in test/services/ be subclassed under Minitest::Spec, and not the Generator test class?

rake db:migrate fails with globalize gem and rails 4.1.7

I'm trying to use the globalize gem with Rails 4.1.7.
Using latest RVM version, os is Ubuntu 12.04, db is postgresql 9.3.
Following the instructions found in readme.md on github i added the translates directive in my model and scaffolded a migration
class Ingredient < ActiveRecord::Base
translates :name, :description
end
class CreateIngredientTranslations < ActiveRecord::Migration
def up
Ingredient.create.translation_table!({
name: :string,
descripion: :text
}, {
migrate_data: true
})
end
def down
Ingredient.drop_translation_table! migrate_data: true
end
end
Then when i do rake db:migrate i get the following error
PG::UndefinedTable: ERROR: relation "ingredient_translations" does not exsist
LINE 5: WHERE a.attrelid = '"ingredient_translations"...
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"ingredient_translations"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
/home/kranz/.rvm/gems/ruby-2.1.4#recipes/gems/activerecord-4.1.7/lib/active_record/connection_adapters/postgresql_adapter.rb:822:in `async_exec'
This is really weird.
Googling around for this kind of error I found a ticket in github
https://github.com/globalize/globalize/issues/288
opened in Dec 2013 and still not closed which seems very similar; the only solution seems to be a hack in globalize code, but i'd prefer not to monkey patching code at that level.
Is it due to the combination of postgres and globalize or there is any other solution to this?