ruby: unable to use logger with rspec - ruby

I am trying to add logging to a simple rspec test. I am using Watir to drive Chrome within the spec and this works fine. I am unable to get logs using the "Logger" library.
This is my spec:
require 'rubygems'
require 'watir-webdriver'
require 'rspec'
require 'logger'
describe 'ui tests' do
let(:browser) { browser ||= Watir::Browser.new :chrome }
let(:log) {
log = Logger.new(STDOUT)
log = Logger.new('watir.tests.log', 'daily')
log.level = Logger::DEBUG
}
before {
browser.goto 'http://translate.google.com'
}
after { browser.close }
context 'simple tests' do
it 'simple test' do
log.info("Running simple test")
browser.text_field(:id => "source").set("ost")
# actual test/asserts here
end
end
end
The problem is that I am unable to call any logging method such as log.info inside the example. I get this error:
Failures:
1) ui tests simple tests simple test
Failure/Error: log.info("Running simple test")
NoMethodError:
undefined method `info' for 0:Fixnum
Why is this failing? Is it a scope issue? If I comment out the log.info the spec runs fine. I can use any methods on the "browser" object (for example, the call to browser.text_field) inside the example without a problem.
Where I am going wrong?

The value of log is the last thing evaluated inside the let(:log) { } block, which is Logger::DEBUG. This constant just corresponds to the Fixnum 0, and there's no method called info for 0. Try this instead:
let(:log) {
Logger.new(STDOUT).tap { |l| l.level = Logger::DEBUG }
}
By the way, what are you trying to do with setting log = Logger.new(STDOUT) and then immediately reassigning log = Logger.new('watir.tests.log', 'daily')?

Related

Uninitialized constant NameError in Rspec

When I run rails c, I can call the following class and the method works:
test = SlackService::BoardGameNotifier
test.create_alert("test")
>>method works
I'm trying to set this up in rspec like this:
require 'spec_helper'
require 'slack-notifier'
RSpec.describe SlackService::BoardGameNotifier do
describe '#notify' do
#notifier = SlackService::BoardGameNotifier
it 'pings Slack' do
error = nil
message = "test"
expect(notifier).to receive(:ping).with(message)
notifier.send_message()
end
end
end
But I keep getting the error:
NameError:
uninitialized constant SlackService
Does this have to do with how I set up the module?
My current setup:
slack_service/board_game_notifier.rb
module SlackService
class BoardGameNotifier < BaseNotifier
WEBHOOK_URL = Rails.configuration.x.slack.url
DEFAULT_OPTIONS = {
channel: "board-games-channel",
text: "board games alert",
username: "bot",
}
def create_alert(message)
message #testing
end
end
end
slack_service/base_notifier.rb
module SlackService
class BaseNotifier
include Singleton
def initialize
webhook_url = self.class::WEBHOOK_URL
options = self.class::DEFAULT_OPTIONS
#notifier = Slack::Notifier.new(webhook_url, options)
end
def self.send_message
message = instance.create_alert("test")
instance.notify(message)
end
def notify(message)
#notifier.post blocks: message
end
end
end
Add this to your spec_helper.rb
# spec_helper.rb
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../config/environment", __dir__)
When running RSpec, Rails doesn't automatically boot up, and therefore doesn't automatically load all the libraries.
Also, I'd suggest creating a .rspec in your app's root folder with the following lines so that spec_helper is automatically loaded for all your RSpec tests:
# .rspec
--format documentation
--color
--require spec_helper
I would use the described_class from Rspec
require 'spec_helper'
require 'slack-notifier'
RSpec.describe ::SlackService::BoardGameNotifier do
describe '#notify' do
it 'pings Slack' do
error = nil
message = "test"
expect(described_class).to receive(:ping).with(message)
notifier.send_message()
end
end
end

Unable to verify expectations in a ruby class

I have a Class definition as below:
def initialize(driver)
#driver = driver
end
def verify_page(username)
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
btnSettings = wait.until { #driver.find_element(:xpath => "//a[#href='/UserManagement/MyAccount']") }
expect(btnSettings.text).to eq('Portal Administrator' + ' -- ' + username)
end
end
When I run the code that calls the 'verify' method of this class, I get the error:
undefined method `expect' for #<PortalHomePage:0x00000003b1d188>
How do i get past this problem?
In order to use rspec expectations.
Please do the following in your env.rb file
require 'rspec'
include RSpec::Matchers
This will solve your current problem
Comment for more information.
Hope it helps!!

Automatic Airbrake errors with plain Ruby (no Rails or Sinatra)

Is there a way to integrate Airbrake with a pure Ruby project (not rails or sinatra) so that unanticipated errors get reported? I have it set up and I am able to catch errors by calling Airbrake.notify_or_ignore and passing in the exception, but I can't get it to report errors without explicitly calling this.
The following is the code that works for explicitly calling Airbrake.notify but doesn't work for sending errors to Airbrake without explicitly calling notify:
require 'airbrake'
Airbrake.configure do |config|
config.api_key = ENV['AIRBRAKE_API_KEY']
config.development_environments = []
config.ignore_only = []
end
I tried adding Rack as a middleware with the following code:
require 'rack'
require 'airbrake'
Airbrake.configure do |config|
config.api_key = ENV['AIRBRAKE_API_KEY']
config.development_environments = []
config.ignore_only = []
end
app = Rack::Builder.app do
run lambda { |env| raise "Rack down" }
end
use Airbrake::Rack
run app
But I get an "undefined method `use' for main:Object (NoMethodError)"
Any thoughts?
Copied from Mark's comment's link to airbrake for future googlers:
# code at http://gist.github.com/3350
# tests at http://gist.github.com/3354
class Airbrake < ActiveResource::Base
self.site = "http://your_account.airbrake.io"
class << self
##auth_token = 'your_auth_token'
def find(*arguments)
arguments = append_auth_token_to_params(*arguments)
super(*arguments)
end
def append_auth_token_to_params(*arguments)
opts = arguments.last.is_a?(Hash) ? arguments.pop : {}
opts = opts.has_key?(:params) ? opts : opts.merge(:params => {})
opts[:params] = opts[:params].merge(:auth_token => ##auth_token)
arguments << opts
arguments
end
end
end
class Error < Airbrake
end
# Errors are paginated. You get 30 at a time.
#errors = Error.find :all
#errors = Error.find :all, :params => { :page => 2 }

not able to find installed Gem in ruby program

hi getting error which is not understand able i am new to ruby so please help .
i checked all thing which is possible for me.
require 'rubygems'
require 'selenium-webdriver'
require 'test/unit'
class SeleniumTest < Test::Unit::TestCase
driver = Selenium::WebDriver.for :firefox
driver.get "http://localhost:9000/assets/build/index.html#/login"
element = driver.find_element :name => "email"
element.send_keys "kaushik#abc.com"
element = driver.find_element :name => "password"
element.send_keys "password"
element.submit
page.find(:xpath, "//a[#href='#/courses/new']").click
#click_link ("//a[#href='#/courses/new']")
puts "Page title is #{driver.title}"
#page.should have_selector(:link_or_button, ' Create New Course...')
wait = Selenium::WebDriver::Wait.new(:timeout => 2000)
driver.quit
end
getting This error:-
TestClass.rb:7:in `<class:SeleniumTest>': undefined local variable or method `logger' for SeleniumTest:Class (NameError)
from TestClass.rb:6:in `<main>'
It seems that you didn't included the complete source code.
Besides that, all you code is bare in class SeleniumTest. You should put your code into the appropriate method or methods.
This type of errors are generated when objects or methods are not created or not scoped well.
In your case, the error message is telling you that the object logger in line 7 of you script does not exist.
As I can see from your source code, line 7 falls into the class definition. I guess you have something like
logger.log 'logging text'
in that line but you delete it from your post, and in lines 4 and 5 you have something like:
require 'logger'
logger = Logger.new('file.log')
If that is the case, you could put logger = Logger.new('file.log') inside the class definition, or define an instance object of type Logger inside the SeleniumClass class, or a global method or something other for logging messages.
Examples:
class SeleniumTest < Test::Unit::TestCase
logger = Logger.new('file.log')
logger.log "logging text"
...
end
or
class SeleniumTest < Test::Unit::TestCase
def initialize
#logger = Logger.new('file.log')
end
def log(message)
#logger.log mesage
end
...
def some_method_with_your_code
...
log "logging text"
...
end
end
st = SeleniumTest.new
st.some_method_with_your_code
... or something similar...
I hope this can help you solve your problem.
If not, you should put the complete source code and tell us what are you trying to do!

Watir / MiniTest - Undefined local variable or method 'browser'

I have 66 watir scripts that I have been creating over the past week to automate testing on the clients website.
However I have recently found out about a test framework called MiniTest which I am trying to implement now.
The reason I have set the URL as a variable is because there are 5 different sites that these tests need to run on so when they want me to run my pack on a different website I just need to update that 1 variable and not in each individual test.
require 'minitest/autorun'
require "watir-webdriver"
class MPTEST < MiniTest::Unit::TestCase
def setup()
url = "http://thewebsite.com/"
$browser = Watir::Browser.new :chrome
$browser.goto url
end
def test_myTestCase
$browser.link(:text, "Submit your CV").click
sleep(2)
$browser.button(:value,"Submit").click
assert($browser.label.text.includes?("This field is required"))
def teardown
$browser.close
end
end
When running that I receive the following output:
NameError: undefined local variable or method 'browser' for #<MPTEST:0x4cc72f8>c:/directory stuff...
Any ideas?
EDIT I have browser working however now there is an issue with my assert:
New code:
require 'minitest/autorun'
require "watir-webdriver"
class MPTEST < MiniTest::Unit::TestCase
def setup()
url ="http://thewebsite.com"
$browser = Watir::Browser.new :chrome
$browser.goto url
end
def test_myTestCase
$browser.link(:text, "Submit your CV").click
sleep(2)
$browser.button(:value,"Submit").click
assert($browser.label.text.includes?("This field is required"))
end
def teardown
$browser.close
end
end
And the error is:
NoMEthodError: undefined method 'includes?' for "":String
it seems to me you can you use #browser instead of $browser (but the problem might be not in this code)
The exception
NoMEthodError: undefined method 'includes?' for "":String
Is due to strings, in this case the value returned by $browser.label.text do not have an includes? method.
The method you actually want is include? (no plural):
assert($browser.label.text.include?("This field is required"))

Resources