Kamilski81
Kamilski81

Reputation: 15107

NameError: undefined local variable or method `logger'

When I run 'script/server' everything works fine, but when I run my unit tests (rake test:units), I get the error below, and am not sure how to solve this.

Error

NameError: undefined local variable or method `logger' for #<GiveawayEligibleMemberTest:0x10477dff8>
    /Users/kamilski81/Sites/pe/vitality_mall/vendor/rails/actionpack/lib/action_controller/test_process.rb:471:in `method_missing'
    /Users/kamilski81/Sites/pe/vitality_mall/lib/update_giveaway_eligible_members.rb:17:in `is_valid_checksum?'
    /Users/kamilski81/Sites/pe/vitality_mall/test/unit/giveaway_eligible_member_test.rb:26:in `test_that_checksum_is_valid'
    /Users/kamilski81/Sites/pe/vitality_mall/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb:60:in `__send__'
    /Users/kamilski81/Sites/pe/vitality_mall/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb:60:in `run'

I tried putting:

class Test::Unit::TestCase
  RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
  RAILS_DEFAULT_LOGGER.level = Logger::WARN

  logger = Logger.new(STDOUT)
  logger.level = Logger::WARN
end

Here is the code that is using my logger:

def is_valid_checksum?(csv_arr)
  expected_row_count = csv_arr[0][3].to_i
  logger.debug "Expected record count: #{expected_row_count}"
  actual_row_count = csv_arr.nitems - 1
  logger.debug "Actual record count: #{actual_row_count}"
  checksum_valid = false
  if expected_row_count == actual_row_count
    logger.debug "Checksum is valid"
    checksum_valid = true
  end

  return checksum_valid
end

But this still does not solve the error

Upvotes: 37

Views: 23515

Answers (3)

mbillard
mbillard

Reputation: 38842

You can use the Rails logger outside of models and controllers:

Rails.logger.info "..."

Source

Upvotes: 77

diedthreetimes
diedthreetimes

Reputation: 4115

The logger method isn't available to test cases instance methods.

You have defined a local variable in your class definition but this isn't enough. The logger variable falls out of scope once the class is initialized. You may be looking for a class variable (@@logger). But a cleaner solution would be wrapping it in a method like this.

class Test::Unit::TestCase
  def logger
    RAILS_DEFAULT_LOGGER ||= Logger.new(STDOUT)
  end
end

Notice this code will use the default logger if it is available (which it should be). If this isn't desired, you can make your own just as easily.

def logger
  @logger ||= Logger.new(STDOUT)
end

Upvotes: 6

naren
naren

Reputation: 937

you should use RAILS_DEFAULT_LOGGER.debug the constant in your test case is_valid_checksum? not the variable logger(class level variable ) which cannot be used in a instance method.

I would suggest to wrap the code in a instance method something like

def logger
  logger = Logger.new(STDOUT)
  logger.level = Logger::WARN
  logger
end

and then use logger

Upvotes: 0

Related Questions