UserMailer failing in Delayed::Job - ruby-on-rails

I'm trying to send an email with Delayed::Job in Rails 5 like so: UserMailer.delay.test("my message", "email#example.com"). Unfortunately, it doesn't work. It gives this error:
FAILED (0 prior attempts) with ArgumentError: unknown command 'h'
or, sometimes,
FAILED (0 prior attempts) with NoMethodError: undefined methoddeliver' for false:FalseClass`
The stack trace is pretty cryptic.
I can run other methods asynchronously by appending handle_asynchronously :some_method after any method.
And UserMailer.test("my message", "email#example.com").deliver_now works fine. How can I debug this issue? Is my syntax wrong?

It's because my UserMailer method was named test, which doesn't seem to work in Delayed::Job

Related

undefined method `+' for nil:NilClass in sample saml application

Trying to follow the setup here to create a simple SAML application (full project I got here).
I went through and did the setup
bundle install
rails s
This went fine, but when I navigate to
http://localhost:3000/
I get hit with
NoMethodError in SamlController#init
undefined method `+' for nil:NilClass
Extracted source (around line #9):
def init
request = OneLogin::RubySaml::Authrequest.new
direct_to(request.create(saml_settings))
end
def consume
I added some logging to check nil status of request and saml_settings but that seems to return false for both of them
puts request.nil?
puts saml_settings.nil?
Error trace:
Processing by SamlController#init as HTML
false
false
Created AuthnRequest: <samlp:AuthnRequest AssertionConsumerServiceURL='http://localhost:3000/saml/consume' ID='_394fa0a0-f313-0135-85a4-6a0001e18280' IssueInstant='2018-02-13T17:42:45Z' Version='2.0' xmlns:saml='urn:oasis:names:tc:SAML:2.0:assertion' xmlns:samlp='urn:oasis:names:tc:SAML:2.0:protocol'><saml:Issuer>http://localhost:3000/saml/consume</saml:Issuer></samlp:AuthnRequest>
Completed 500 Internal Server Error in 15ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `+' for nil:NilClass):
app/controllers/saml_controller.rb:9:in `init'
(Note: the error is line 5, it says line 9 for me because of debug logging I added)
I'm not too sure what else it could be, not sure what method it can't find and what is nil?
I have never messed with ruby stuff, but from my initial looks I'm not sure where the nil is coming from, the logs show the request being created so not sure. Any help would be appreciated, thanks!
Firstly I think you're using a pretty old ruby-saml gem version. That might be the problem.
I haven't tested your code, but it seems to me that you forgot to set idp_sso_target_url in your settings, and apparently that's the only place it can throw the exception you got. https://github.com/onelogin/ruby-saml/blob/v1.1.2/lib/onelogin/ruby-saml/authrequest.rb#L39
Posting the answer here, turns out that i was using a metadata url for the OKTA_METADATA environment variable.
Had to modify
settings = idp_metadata_parser.parse(ENV['OKTA_METADATA'])
to
settings = idp_metadata_parser.parse_remote(ENV['OKTA_METADATA'])
where
OKTA_METADATA=http://blahblahblah.com/metadata

rails 4 - active job - wrong number of arguments (0 for 1) even though im passing 1 argument

Here I call the job - passing in procedure:
ProcedureDayAfterJob.set(wait_until: reminder_for_jo).perform_later(procedure)
Here is the job itself - taking procedure as argument:
class ProcedureDayAfterJob < ActiveJob::Base
queue_as :mailers
def perform(procedure)
return if procedure.upcoming?
Admin::NotificationMailer.procedure_day_after(procedure).deliver_later
end
end
Here is method in mailer - taking procedure as argument:
def procedure_day_after(procedure)
#procedure = procedure
mail(
# hiding who im sending to
)
end
And here is the error I'm getting:
2017-12-15T19:25:57.365Z 9222 TID-oxvg7jsso ERROR: !!! ERROR HANDLER
THREW AN ERROR !!!
2017-12-15T19:25:57.365Z 9222 TID-oxvg7jsso ERROR: wrong number of
arguments (0 for 1)
2017-12-15T19:25:57.365Z 9222 TID-oxvg7jsso ERROR:
/Users/foreverlabs/foreverlabs/app/jobs/procedure_day_after_job.rb:4:in
`perform'
I'm passing in the argument to each method so can anybody figure out what's going on?
I have seen this happen due to a typo in the initializer for the Service/Class being called within the job.
It is usually misleading with the single line errors where the only helpful info is the line number and file it is erroring on. With that, and looking at your queue log, it shows it is coming from the 4th line which is inside the perform method itself, and where the code has been redacted.
Check the class you are calling on this line to see if "initialize" is misspelled somehow (I do it from time to time myself),because doing such would cause the constructor to disable, as well as cause the class to expect zero arguments.
I'm sure you have fixed this, but hopefully this will help someone else in the future.

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.

RubyOnRails Rake test failures

i try to create internet shop from "Agile Web Development with Rails 4". When i write 'rake test', i get this message:
$ rake test
Run options: --seed 54737
# Running:
........F...F
Finished in 0.279167s, 46.5671 runs/s, 118.2088 assertions/s.
1) Failure:
ProductTest#test__product_is_not_valid_without_a_unique_title_-_i18n [/Users/roni/Coding/Ruby/depot/test/models/product_test.rb:82]:
--- expected
+++ actual
## -1 +1 ##
-["translation missing: en.activerecord.errors.messages.taken"]
+["has already been taken"]
2) Failure:
ProductTest#test_product_price_must_be_positive [/Users/roni/Coding/Ruby/depot/test/models/product_test.rb:25]:
Failed assertion, no message given.
13 runs, 33 assertions, 2 failures, 0 errors, 0 skips
It's product_test.rb
http://pastebin.com/1f5zkDwa
Please, help me, what i did wrong?
It appears the location of error messages for the 'already taken' case has been changed in Rails 4 and the book must have missed this update.
The error message has been moved to the namespace where also other validation error messages of ActiveModel reside, to the errors.messages. Hence, the 'taken' error message was set under key activerecord.errors.messages.taken, but in Rails 4 it is under errors.messages.taken.
If you update line 82 in your test with the new key, the test should pass.
Just like the message states, you don't have translation for en.activerecord.errors.messages.taken in config/locales.
Also, in assert_equal method, first argument is actual value, while second argument is expected value. So it should be:
assert_equal product.errors[:title], ["has already been taken"]
in this case.

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

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

Resources