Setting more than one cookie in integration test causes NoMethodError after upgrading rails 2.3 - ruby-on-rails

This all worked fine in rails 2.3.5, but when a contractor firm upgraded directly to 2.3.14 suddenly all the integration tests were saying:
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
I have a before_filter on my ApplicationController that sets a bunch of cookies for some javascript to use, and I found that if I comment out all but one of the lines that sets cookie values, it works fine, and it doesn't matter which line I leave in.
before_filter :set_cookies
def set_cookies
cookies['logged_in'] = (logged_in ? 'y' : 'n')
cookies['gets_premium'] = (gets_premium ? 'y' : 'n')
cookies['is_admin'] = (is_admin ? 'y' : 'n')
end
If only one of these lines is active, everything is fine in the integration test, otherwise I get the error above. For example, consider the following test / response:
test "foo" do
get '/'
end
$ ruby -I"lib:test" test/integration/foo_test.rb -n test_foo -v
Loaded suite test/integration/foo_test
Started
test_foo(FooTest): E
Finished in 5.112648 seconds.
1) Error:
test_foo(FooTest):
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
test/integration/foo_test.rb:269:in `test_foo'
1 tests, 0 assertions, 0 failures, 1 errors
But if any two of those cookie setting lines are commented out, I get:
$ ruby -I"lib:test" test/integration/foo_test.rb -n test_foo -v
Loaded suite test/integration/foo_test
Started
test_foo(FooTest): .
Finished in 1.780388 seconds.
1 tests, 0 assertions, 0 failures, 0 errors
The website running in development and production mode works fine - this is just a matter of getting the tests passing. Also, with debugging output I have verified that the error does not get thrown in the method where the cookies get set, that all executes fine, it's somewhere later that the error happens (but the backtrace doesn't tell me where)

This turned out to be a bug in how rack rack writes cookies to the client along with the session cookie. Rack was including double newlines and omitting semi-colons.
Browsers like firefox can handle mildly malformed cookie data, but the integration test client couldn't.
To fix this I had to rewrite the cookie header before sending it to the client.
In environment.rb:
require 'rack_rails_cookie_header_hack'
And in lib/rack_rails_cookie_header_hack.rb:
class RackRailsCookieHeaderHack
def initialize(app)
#app = app
end
def call(env)
status, headers, body = #app.call(env)
if headers['Set-Cookie']
cookies = headers['Set-Cookie']
cookies = cookies.split("\n") if is_str = cookies.is_a?(String)
if cookies.respond_to?(:collect!)
cookies.collect! { |h| h.strip }
cookies.delete_if { |h| h.empty? }
cookies.collect! { |h| h.include?(';') ? h : h + ';' }
end
headers['Set-Cookie'] = is_str ? cookies.join("\n").strip : cookies
end
[status, headers, body]
end
end
Sorry the sources aren't articulated, I actually fixed this awhile ago and came across this questions and figured I'd post my patch.

L0ne's answer works for me, but you also need to include this - it can go at the bottom of lib/rack_rails_cookie_header_hack.rb, providing you're requiring it at the bottom of your environment.rb file - ie after the Rails::Initializer has run:
ActionController::Dispatcher.middleware.insert_before(ActionController::Base.session_store, RackRailsCookieHeaderHack)

Old forgotten issues...
I haven't tested Lone's fix but he has correctly identified the problem. If you catch the exception and print using exception.backtrace, you'll see that the problem is caused by
gems/actionpack/lib/action_controller/integration.rb:329
The offending code is this:
cookies.each do |cookie|
name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2]
#cookies[name] = value
end
If you're like me, and you're only interested in some super quick integration tests, and don't care too much about future maintainability (since it's rails 2), then you can just add a conditional filter in that method
cookies.each do |cookie|
unless cookie.blank?
name, value = cookie.match(/^([^=]*)=([^;]*);/)[1,2]
#cookies[name] = value
end
end
and problem solved

Related

ElasticSearch Rails resource_already_exists_exception when running tests

I'm trying to run one of my tests, which makes a search, trying to assert the inclusion of records in the search result, but in the meantime, I'm receiving a Elasticsearch::Transport::Transport::Errors::BadRequest error:
SearchTest#test_simple_test_returns_product:
Elasticsearch::Transport::Transport::Errors::BadRequest: [400]
{
"error":{
"root_cause":[
{
"type":"resource_already_exists_exception",
"reason":"index [app_application_test_products/FTt1YC6eQrCw2XwJuqjmDw] already exists",
"index_uuid":"FTt1YC6eQrCw2XwJuqjmDw",
"index":"app_application_test_products"
}
],
"type":"resource_already_exists_exception",
"reason":"index [app_application_test_products/FTt1YC6eQrCw2XwJuqjmDw] already exists",
"index_uuid":"FTt1YC6eQrCw2XwJuqjmDw",
"index":"app_application_test_products"
},
"status":400
}
When I perform a search in development, it works as expected, but in tests is throwing such error, within the test I've added an import and an index refresh, nothing else:
class SearchTest < ActiveSupport::TestCase
setup do
Product.import force: true
Product.__elasticsearch__.refresh_index!
end
test "simple test returns product" do
product = products(:one)
I18n.locale = product.market.lang
search = Search.new(
category: product.category.custom_slug,
page: 1,
market_id: product.market_id,
status: "active",
seed: Date.today.to_time.to_i
)
assert_includes search.results.records, products(:one)
assert_includes search.results.records, products(:two)
assert_not_includes search.results.records, products(:three)
end
end
Any help is appreciated, as any hint to improve the code.
I'm using:
# Gemfile
gem 'minitest', '5.10.1'
# Gemfile.lock
elasticsearch (6.1.0)
elasticsearch-model (6.0.0)
elasticsearch-rails (6.0.0)
minitest (= 5.10.1)
I'm glad you found the root cause for your specific issue.
I ran into a similar issue with ruby-on-rails gem for elasticsearch. While the mappings are all fine, i did get the exact same error message. Leaving my answer here so that anyone else who comes here can get more help.
After a lot of trying and error, eventually figured out that the reason is that it's timing out on the create index.
If you change the client timeout to 60 seconds (it failed with 30 seconds), it was able to create the index successfully without causing this intermittent error.
connection_hash = {
hosts: [ "localhost:9220" ]
reload_connections: true
adapter: :httpclient
retry_on_failure: 2
request_timeout: 60
}
es_connection_client = Elasticsearch::Client.new(connection_hash)
Also, found this issue that is related and was closed after a similar answer.
https://github.com/ankane/searchkick/issues/843#issuecomment-384136164
I was using time freezing in multiple specs, so creating a new object with the same created_at time as the object in the previous spec was causing the resource_already_exists_exception error. Slightly adjusting the timestamp to freeze for each spec fixed the problem.
I had the wrong mappings in my model. Instead using the type option, I was using index, what made ElasticSearch to create a multiple mapping. Which isn't available since the version 6.4 (I guess).

Rails 5: Error when removed quiet_assets_path from development.rb

I have been trying to upgrade my app from Rails 4 to Rails 5. In my Rails 4 version I have quiet_assets_path set but in Rails 5 it is not required. But when I removed that tried to start the server I am getting the following error,
> ruby-2.2.2/gems/rack-mini-profiler-0.10.2/lib/mini_profiler_rails/railtie.rb:93:in
> `>': comparison of Fixnum with nil failed (ArgumentError) from
> /Users/Admin/.rvm/gems/ruby-2.2.2/gems/rack-mini-profiler-0.10.2/lib/mini_profiler_rails/railtie.rb:93:in
> `block in <class:Railtie>'
Can someone help me with this?
Edit:
Following is my rack_profiler.rb,
if Rails.env.development? || Rails.env.production?
require 'rack-mini-profiler'
# initialization is skipped so trigger it
Rack::MiniProfilerRails.initialize!(Rails.application)
Rack::MiniProfiler.config.skip_schema_queries = true
Rack::MiniProfiler.config.skip_paths += %w(/admin/sidekiq)
Rails.application.middleware.delete(Rack::MiniProfiler)
Rails.application.middleware.insert_after(Rack::Deflater, Rack::MiniProfiler)
end
When I comment the delete line then server is starting but if the line uncommented then the server breaks.
thanks for the update. First of all, do you use Rack::Deflater middleware in development environment too?
I think this issue might help you. It basically says that in Rails all delete middleware operations are issued at the end. You can use the swap method as described in the above issue.
If you search the repo issues for "Deflater" you'll find a lot of results, but I believe the above contains your fix.

Devise Sign-Up Route End of File Reached Error

I've searched all over the internet for an answer to this error, but nothing seems to address it directly or effectively.
I am using Devise in a Rails application and whenever I go to the users/sign_up page and submit the data, it will not submit properly and Rails gives me the error:
"EOFError at /users
end of file reached"
Rails also includes this trace:
rbuf_fill/Users/john/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/net/protocol.rb
BUFSIZE = 1024 * 16
def rbuf_fill
begin
#rbuf << #io.read_nonblock(BUFSIZE)
rescue IO::WaitReadable
if IO.select([#io], nil, nil, #read_timeout)
retry
else
raise Net::ReadTimeout
Which I have had no luck following.
From other posts, I believe something may be wrong with the mailer setup, but I've tried every solution recommended and I'm still getting this error. Currently, I have config.mailer_sender = SUPPORT_EMAIL setup in the config/initializers/devise.rb file.
I would greatly appreciate any suggestions anyone has, as I've spent a ton of time on this with no luck.

Rails App with Sinatra engine - How to avoid rails errors?

Problem: When running specs the output is very confusing, instead of saying where the error lies it just throws misleading errors
This is inside the rails lib folder, and it's mounted on the routes.rb
# lib/engines/users/app.rb
module Engines
module Users
class App < Sinatra::Base
get '/api/v1/users/me' do
raise 'runtime error here'
end
get '/api/v1/another-route' do
# something here
status 200
end
end
end
end
The spec file looks something like this:
it 'returns a 200' do
get '/api/v1/users/me', auth_attributes
expect(last_response.body).to eq 'something' # added to clarify my point, it's not the response status that I care of.
expect(last_response.status).to be 200
end
error:
Failure/Error: expect(last_response.status).to be 200
expected #<Fixnum:401> => 200
got #<Fixnum:1001> => 500
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.
expected error:
RuntimeError:
runtime error here
Another route also fails:
it 'something' do
get '/api/v1/another-route', auth_attributes
expect(last_response.status).to be 401
json = JSON.parse(last_response.body).with_indifferent_access
expect(json[:message]).to eql "You have been revoked access."
end
error: Prints a massive html output which I believe is the rails backtrace html output
expected error: none as this endpoint doesn't raise an error
My question is if there's a way to:
Stop rails from dealing with this, so it gives the actual output
Avoid the entire engine to fail because one route raise exception
I believe that by solving the first point, the second one gets fixed too.
Thank you for your time
In order to solve my problem I've discovered that on the spec_helper the ENV['RACK_ENV'] was not being set, setting it to test resolves the problem and throws the exception I need in order to debug my code.
This happens because https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1832
set :show_exceptions, Proc.new { development? }
development? returned true when in fact should be false (needed the RACK_ENV set to test)
Now I get the correct output.

upgrading 3.12 to 4, run rails s, get stack level too deep error in local_cache_middleware

Used rake rails:update, meticulously updated overwritten files, and have my rspec specs running green. But when I run rails s I hit this:
Unexpected error while processing request: stack level too deep
/Users/Alex/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-4.1.4/lib/active_support/cache/strategy/local_cache_middleware.rb:33
Specifically it is crapping out at response = #app.call(env) (line 26) in the above cited file.
I'm working through checklists to see if I might have missed a configuration setting somewhere. Can anyone give me a clue?
So, first thing I did was get a full backtrace out of the exception by adding:
rescue Exception => e
puts e.backtrace
LocalCacheRegistry.set_cache_for(local_cache_key, nil)
raise
end
Which then revealed one critical line before the cache middleware one I saw before:
/Users/Alex/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-4.1.4/lib/active_support/logger.rb:38
Unexpected error while processing request: stack level too deep
/Users/Alex/.rvm/gems/ruby-2.0.0-p451/gems/activesupport-4.1.4/lib/active_support/cache/strategy/local_cache_middleware.rb:35
I jumped into the listed line which looked like this:
define_method(:level=) do |level|
logger.level = level
super(level)
end
Then searched the rest of my repo to see where I was touching logger.level. (If I hadn't been able to find the call that way, I would've used Kernel#caller.) Ahah, I discover: config/initializers/quiet_assets.rb, hmm what is this? Looks like a monkey-patch I put in an initializer ages ago:
# taken from https://stackoverflow.com/questions/6312448/how-to-disable-logging-of-asset-pipeline-sprockets-messages-in-rails-3-1
if Rails.env.development?
Rails.application.assets.logger = Logger.new('/dev/null')
Rails::Rack::Logger.class_eval do
def call_with_quiet_assets(env)
previous_level = Rails.logger.level
Rails.logger.level = Logger::ERROR if env['PATH_INFO'] =~ %r{^/assets/}
call_without_quiet_assets(env)
ensure
Rails.logger.level = previous_level
end
alias_method_chain :call, :quiet_assets
end
end
When I commented this out, poof, my error was gone and I was able to load up a page in browser. Now I've deleted the initializer and am good to go. :) For those that used How to disable logging of asset pipeline (sprockets) messages in Rails 3.1?, make sure to remove it when you upgrade!

Resources