Trying to write a custom irb for a gem to ease debugging. At the point where the shell loads and you can use it like ruby console but running into this wall
MyClass.get_last_instance
=>
_.attributes
=> {'attribute'=> 'test'}
The instance was found but a blank string is echo'ed. Here are the requires involved in starting the shell
require 'irb'
require 'irb/completion'
require 'debugger'
I tried reading through the rails source code, didn't get very far, mostly because I didn't really know what I was looking for. I think I'm just missing a require of a part of rails that echos objects.
create a .irbrc in your home path for ubuntu/osx and use the below code, it will work. Also you can add additional gems also debugger or irb
# print SQL to STDOUT
if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
require 'logger'
end
# Autocomplete
require 'irb/completion'
# Prompt behavior
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]
# History
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
# Easily print methods local to an object's class
class Object
def local_methods
(methods - Object.instance_methods).sort
end
end
# copy a string to the clipboard
def pbcopy(string)
`echo "#{string}" | pbcopy`
string
end
require "rubygems"
Related
My rails app recently moved from Rails 3 to Rails 4 and I've been trying to run rspec on individual specs (controllers, models, etc.) and it seems to be having an issue actually locating the object. For example, when I try to run the following code it errors with an uninitialized constant error. This seems to be happening for multiple controllers. I've already tried deleting the rails_helper.rb and spec_helper.rb and running rails generate rspec:install but it doesn't seem to resolve the error. Why can't it find the controllers?
What I'm Trying to execute
-> rspec spec/controllers/activity_controller_spec.rb
/Users/osx_user/rails_projects/tealeaf_rails/ltbweb/spec/controllers/activity_controller_spec.rb:4:in `<top (required)>': uninitialized constant ActivitiesController (NameError)
rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
spec_helper.rb
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause this
# file to always be loaded, without a need to explicitly require it in any files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Limits the available syntax to the non-monkey patched syntax that is recommended.
# For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
I added
require File.expand_path("../../config/environment", __FILE__)
to the spec_helper.rb file and this resolved the error. I'm not sure why the spec_helper needs this, but I think it has something to do with Rails' ability to locate a file's path relative to another file, and I suspect this was messing up RSpec's ability to find the appropriate controllers, models, etc.
I did some research and found that previously we were on RSpec 2.14 and we're now on 3.2, and I think there may be some differences in the way rspec uses these two files. In our old spec_helper file we had this line:
require File.expand_path("../../config/environment", __FILE__)
I have added
--require rails_helper
in .rspec in my rails application, it resolves the error.
Ensure require 'rails_helper' is at the top of your spec.
It looks like you have upgraded rspec. That require line was moved from spec_helper to the new file rails_helper. You probably failed to change the line at the top of your spec file to include rails_helper instead of spec_helper. (note that rails_helper in turn includes spec_helper)
Could it simply be that you're referring to ActivitiesController and yet the controller is defined as ActivityController.
It says...
uninitialized constant ActivitiesController
and yet your spec file is called...
rspec spec/controllers/activity_controller_spec.rb
In my case, I have my controllers inside of 'api/v1/' so I had to define in the spec file something like:
describes Api::V1::ActivitiesController do
I hope this can help you ;)
I have multiple ruby test cases for selenium-webdriver and all the files are sharing the same functions. is there any way to create a global file and include the file to these test cases instead of typing them over and over again
for example - I create a file setup.rb
def setup
#driver = Selenium::WebDriver.for :firefox
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
end
then in my test_file.rb I start
require setup
setup
#driver.find_element(:xpath => '//span[text()="войти"]').click
There is an error
NoMethodError:
undefined method `find_element' for nil:NilClass
Change it to a global variable from an instance variable. Make it $driver instead of #driver and you shouldn't have a problem. Change it to something like..
def self_setup
$driver = Selenium::WebDriver.for :firefox
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
end
and then
require "./setup.rb"
setup.setup
$driver.find_element(:xpath => '//span[text()="войти"]').click
That should work. You'd probably want to go to a page first before you look for that xpath though. setup will only open up a new instance of firefox webdriver. Also I would suggest changing the name of setup.rb so it can be foo.setup insead of setup.setup. I use Lib.rb for the methods I want to be able to call regularly so for instance one would be Lib.signin_admin
Hope this works for you.
In response to your example, I think you forgot to include the setup module (you did put your method definition inside a module, right?). Also, the comment that mentions assigning the driver as a global variable (by naming it with a starting dollar sign) is a good idea. So things would look like this...
setup.rb
module Setup
def setup
$driver = Selenium::WebDriver.for :firefox
$wait = Selenium::WebDriver::Wait.new(:timeout => 10)
end
end
test_file.rb
require 'setup'
class SeleniumTest < Test::Unit::TestCase
include Setup # Modules need to be included (mixed-in) in order to be used inside classes
# Setup is automagically called when using TestUnit
$driver.get "http://www.yoururl.com"
$driver.find_element(:xpath => '//span[text()="войти"]').click
end
The downside is that for each new module and file you create, you have to require and include all of the new files and modules you want to use.
The method that I have found to work for me is to create a 'test_helper.rb', and to use a gem called 'require_all' that requires and includes all of the files from the directories you specify.
My test_helper.rb looks something like this:
require "rubygems"
require "require_all"
require "selenium-webdriver"
require "test-unit"
require_all relative_path("../lib/selenium/")
module TestHelpers
include Selenium
def setup
$driver = Selenium::WebDriver.for :firefox
...
end
def teardown
$driver.quit
end
end
And the test_page.rb only requires two lines:
# Line 1: Ensures the test_helper.rb gets loaded from the same directory the test_page.rb resides in
require File.join(File.dirname(__FILE__), 'test_helper')
class TestPage < Test::Unit::TestCase
# Line 2: Module needs mixed in to use its methods
include TestHelpers
def test_page
$driver.get "http://www.mysite.com"
assert $driver.find_element(:css => "div#my_site_logo")
end
end
Trying to go through the tekpub rack tutorial but run into this error.
Boot Error
Something went wrong while loading app.ru
LoadError: cannot load such file -- haiku
There is a file named haiku.rb in the same directory as the app I am trying to run but I get the above error while trying to run the program. Here is the code:
class EnvironmentOutput
def initialize(app=nil)
#app = app
end
def call(env)
out = ""
unless(#app.nil?)
response = #app.call(env)[2]
out+=response
end
env.keys.each {|key| out+="<li>#{key}=#{env[key]}</li>"}
["200",{"Content-Type" => "text/html"},[out]]
end
end
require 'haml'
require 'haiku'
class MyApp
def call(env)
poem = Haiku.new.random
template = File.open("views/index.haml").read
engine = Haml::Engine.new(template)
out = engine.render(Object.new, :poem => poem)
["200",{"Content-Type" => "text/html"}, out]
end
end
use EnvironmentOutput
run MyApp.new
I'm sure its a small error as the code is the same as in the tutorial and it works for him...
Thanks
You'll want to read up on ruby load path (either $LOAD_PATH or $:). By default, ruby has a load path which includes wherever your gems are installed, which is why you can do require 'haml' without providing the full path to where your haml gem is located.
When you type require 'haiku', you're basically telling ruby to look for some file called haiku.rb somewhere in it's load path, and the LoadError comes from ruby not finding your haiku.rb file in any of the directories listed in $LOAD_PATH (or $:, which is just shorthand for $LOAD_PATH).
You can solve this in one of (at least) two ways:
change require 'haiku' to require File.dirname(__FILE__) + '/haiku.rb' to explicitly tell ruby what file to load
add the current working directory to your load path: $:.push(File.dirname(__FILE__)). This way you can keep the require 'haiku' part.
When Rails functions are asking for a translation (I18n.translate), I don't want to analyze their code in order to get the exact scopes etc.
How can I add a debug output into the console for every string that was asked for?
Examples:
I18n.t 'errors.messages.invalid', :scope => :active_record
# Translation for 'activerecord.errors.messages.invalid' (not) found
label(:post, :title)
# Translation for 'activerecord.attributes.post.title' not found
# Translation for 'views.labels.post.title' not found
This is not a very elegant solution, but it's worked for me. I've created an initialiser:
require 'i18n'
if (Rails.env.development? || Rails.env.test?) && ENV['DEBUG_TRANSLATION']
module I18n
class << self
def translate_with_debug(*args)
Rails.logger.debug "Translate : #{args.inspect}"
translate_without_debug(*args)
end
alias_method_chain :translate, :debug
end
end
end
You can then run commands like the following:
$ DEBUG_TRANSLATION=true rake cucumber
...and you'll see all the translations being attempted dumped to STDOUT. I don't consider this production code though, so I've kept it in a Gist, and not checked it into my main project source control at this stage.
Noddy, but it does the job.
Just a small change to put I18n debug messages in the log:
substitute this line:
puts "Translate: #{args.inspect}"
with
Rails.logger.debug "Translate : #{args.inspect}"
Rspec obviously hates me. I kinda hate him back.
#features/step_definitions/custom_steps.rb
Then /^I should see the link "([^\"]*)"$/ do |linked_text|
find_link(linked_text)
end
#link.feature
Then I should see the link "foo"
From terminal:
undefined method `find_link' for #<Cucumber::Rails::World:0x818e02e8> (NoMethodError)
./features/step_definitions/custom_steps.rb:115:in `/^I should see the link "([^\"]*)"$/'
My env.rb file:
#features/support/env.rb
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'webrat'
require 'webrat/core/matchers'
require 'spec/stubs/cucumber'
Scenes::load
Webrat.configure do |config|
config.mode = :rails
config.open_error_files = false # Set to true if you want error pages to pop up in the browser
end
# If you set this to false, any error raised from within your app will bubble
# up to your step definition and out to cucumber unless you catch it somewhere
# on the way. You can make Rails rescue errors and render error pages on a
# per-scenario basis by tagging a scenario or feature with the #allow-rescue tag.
#
# If you set this to true, Rails will rescue all errors and render error
# pages, more or less in the same way your application would behave in the
# default production environment. It's not recommended to do this for all
# of your scenarios, as this makes it hard to discover errors in your application.
ActionController::Base.allow_rescue = false
# If you set this to true, each scenario will run in a database transaction.
# You can still turn off transactions on a per-scenario basis, simply tagging
# a feature or scenario with the #no-txn tag. If you are using Capybara,
# tagging with #culerity or #javascript will also turn transactions off.
#
# If you set this to false, transactions will be off for all scenarios,
# regardless of whether you use #no-txn or not.
#
# Beware that turning transactions off will leave data in your database
# after each scenario, which can lead to hard-to-debug failures in
# subsequent scenarios. If you do this, we recommend you create a Before
# block that will explicitly put your database in a known state.
Cucumber::Rails::World.use_transactional_fixtures = true
# How to clean your database when transactions are turned off. See
# http://github.com/bmabey/database_cleaner for more info.
if defined?(ActiveRecord::Base)
begin
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
rescue LoadError => ignore_if_database_cleaner_not_present
end
end
What is wrong? Thank you.
This error is telling you none of your steps or helpers define this method.
Are you trying to use one of the helpers buried in Webrat? It sounds like you want:
Webrat::Locators.find_link