Is there a way with test::unit Ruby to load gems - ruby

I am trying to use test::unit for testing and the framework I am trying to test requires a particular gem (rhodes)
Can anyone suggest how I can get the gem loaded when I run my tests
Update :: Error Message
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- rho (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from ../../app/Settings/controller.rb:1
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from ../test_helper.rb:4
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
from test_settings.rb:4
My unit test uses require to include test_helper.rb which contains following
$: << "../../app"
require 'rubygems'
require 'rhodes'
require 'test/unit'
require 'Settings/controller'
Settings/controller lives in app and contains
require 'rho'
require 'rho/rhocontroller'
require 'rho/rhoerror'
require 'helpers/browser_helper'
class SettingsController < Rho::RhoController
include BrowserHelper
def index
#msg = #params['msg']
render
end
def login
#msg = #params['msg']
render :action => :login, :back => '/app'
end
def login_callback
errCode = #params['error_code'].to_i
if errCode == 0
# run sync if we were successful
WebView.navigate Rho::RhoConfig.options_path
SyncEngine.dosync
else
if errCode == Rho::RhoError::ERR_CUSTOMSYNCSERVER
#msg = #params['error_message']
end
if !#msg || #msg.length == 0
#msg = Rho::RhoError.new(errCode).message
end
WebView.navigate ( url_for :action => :login, :query => {:msg => #msg} )
end
end
def do_login
if #params['login'] and #params['password']
begin
SyncEngine.login(#params['login'], #params['password'], (url_for :action => :login_callback) )
render :action => :wait
rescue Rho::RhoError => e
#msg = e.message
render :action => :login
end
else
#msg = Rho::RhoError.err_message(Rho::RhoError::ERR_UNATHORIZED) unless #msg && #msg.length > 0
render :action => :login
end
end
def logout
SyncEngine.logout
#msg = "You have been logged out."
render :action => :login
end
def reset
render :action => :reset
end
def do_reset
Rhom::Rhom.database_full_reset
SyncEngine.dosync
#msg = "Database has been reset."
redirect :action => :index, :query => {:msg => #msg}
end
def do_sync
SyncEngine.dosync
#msg = "Sync has been triggered."
redirect :action => :index, :query => {:msg => #msg}
end
end

Edit 2: after looking at your code, I believe the following should work:
Move the lines from test_helper
require 'rubygems'
require 'rhodes'
to the very top of Settings/controller
Or are you thinking of loading it dynamically during setup/teardown (possibly to avoid conflicting dependencies etc.)?
Edit: I wrote up a quick example of testing a simple wrapper around a Watir class (UI manipulator for IE browser).
require 'rubygems'
require 'watir'
require 'test/unit'
class WatirWrapper
def initialize()
#browser = Watir::IE.new()
end
def method_missing(sym, *args, &block)
#browser.send(sym, *args, &block)
end
end
class WatirWrapperTest < Test::Unit::TestCase
def test_goto
#ww = WatirWrapper.new()
#ww.goto('http://www.google.com/')
assert_equal('http://www.google.com/', #ww.url())
end
end

Related

undefined method for calling methode in class

i try to call my methode check_table_exists for check my table. This methode is on my module, and i dont understand why i get this error .
i know #connexion is a Mysql2::Client instance, which doesn't include the module Sgbd. but i dont see how to include my methode ?
./yamlReadFile.rb:44:in `mysql_connection': undefined method `check_table_exists' for #<Mysql2::Client:0x000000033a7750> (NoMethodError)
$LOAD_PATH << '.'
require 'yaml'
require 'rubygems'
require 'mysql2'
require 'creatDatabase'
#binding.pry
class StreamMysql
include Sgbd
def mysql_connection(conf)
#connexion = Mysql2::Client.new(:host => conf['ost'], :username => conf['user'], :password => conf['password'], :table => conf['table'], :port => conf['port'])
if #connexion
puts check_table_exists
#connexion.check_table_exists
puts "connexion etablie"
else
puts "error connexion"
end
rescue Mysql2::Error => e
puts e.errno
puts e.error
#connexion.close
end
def read_config_file
config = YAML::load_file(File.join(__dir__, 'config.yml'))
conf = config['database']
mysql_connection(conf)
end
end
my module file with the mehode check_table_exists
module Sgbd
# class ModuleCreateDatabase
def create_database
end
def check_table_exists
query=("SHOW TABLES;")
end
end
It’s unclear why would you want to include your module in the foreign class, but it’s doable:
Mysql2::Client.include Sgbd
The line above should be put e. g. before class StreamMysql declaration.

Facing issues while calling method of module(having object of class , contained in another ruby file)

I am newbie in ruby and working on making performance automation framework using using 'ruby-jmeter' gem (provided by flood.io)
I have made following files structure
Where payload.rb and request.rb contains my common utility methods . Which I am calling from test.rb
(test.rb would be going to be written by QA ppl)
Performance Automation Framework Structure
request.rb (lying under 'common' folder)
require 'ruby-jmeter' #(Consider any 3rd party gem )
require 'rubygems'
module RubyJmeter
class ExtendedDSL < DSL #'ruby-jmeter' class extending
def get_common_headers()
commonHeaderHashMap = {
'tns' => 'urn:',
'Content-Type' => 'text/xml; charset=utf-8',
'Accept-Language' => 'en-US,en;q=0.5',
'Accept-Encoding' => 'gzip, deflate'
}
return commonHeaderHashMap
end
end
end
class Request
def initialize(dsl)
#dsl = dsl
end
def soap_post_web_request(name,rawBody)
endPoint = '/SoapEndPoint'
post name: name, url: endPoint , raw_body: rawBody do
tempHeaderHashMap = get_common_headers.merge( {'SOAPAction' =>
'urn:'+name} )
finalHeaderArray = []
tempHeaderHashMap.each {|key, value|
localHashMap = Hash.new
localHashMap = {:name => key, :value => value}
finalHeaderArray << localHashMap
}
header finalHeaderArray
end # End of soapCall
end #end of soap_post_web_request
# Passes method calls through to the underlying DSL (ruby-jmeter).
def method_missing method, *args, &block
#dsl.__send__ method, *args, &block
end
end
wrappingclasses_under_single_module.rb (lying under 'common' folder)
require 'rubygems'
require 'ruby-jmeter'
require 'require_all'
require_all './'
module PerformanceAutomation
def self.MyRequest
Request.new(self)
end
end
test.rb (lying under 'testflow->simpleflow' folder)
require 'ruby-jmeter' #(Consider any 3rd party gem )
require 'rubygems'
require 'require_all' #(another 3rd party gem)
require_all '../../common/'
include PerformanceAutomation
test name:'JiraAnalyticsPerformanceFlow' do
threads name: 'NoOfUsers',scheduler: false,continue_forever: false,
count: 1 do
PerformanceAutomation.MyRequest.soap_post_web_request('soapRequestmethodName',rawdata)# End of Soap request 'soapRequestmethodName'
end # End of TestPlan
view_results_tree
puts "JMX FILE IS GONNA SAVED # "+Dir.pwd+"/CreatedJMeter_DB2Navigation.jmx"
end.jmx(file: Dir.pwd+"/CreatedJMeter_DB2Navigation.jmx")
When running test.rb , I am getting following error
`<top (required)>': uninitialized constant PerformanceAutomation (NameError)
Edit (It is working fine now)
Updated common utility files by using
request.rb
module RubyJmeter
class ExtendedDSL < DSL
def get_admin_common_headers()
commonHeaderHashMap = {
'X-XSRF-TOKEN' => '${COOKIE_XSRF-TOKEN}',
'Content-Type' => 'text/xml; charset=utf-8',
'Accept-Language' => 'en-US,en;q=0.5',
'Accept-Encoding' => 'gzip, deflate'
}
return commonHeaderHashMap
end
end
end
module API
class AdminWebService
def initialize(dsl)
#dsl = dsl
end
## Admin request for 'get_space_properties'
def get_space_properties(rawBody)
endPoint = "/AdminService.asmx"
post name: "admin_GetSpaceProperties", url: endPoint ,
raw_body:rawBody do
tempHeaderHashMap = get_admin_common_headers.merge( {'SOAPAction' =>
'http://example.com/GetSpaceProperties'} )
finalHeaderArray = []
tempHeaderHashMap.each {|key, value|
localHashMap = Hash.new
localHashMap = {:name => key, :value => value}
finalHeaderArray << localHashMap
}
header finalHeaderArray
end # End get_space_properties
end
test.rb
require 'rubygems'
require 'ruby-jmeter'
require 'require_all'
require_all '../../../common/'
defaults domain: 'example.com', protocol: 'http', connect_timeout:
'2000', response_timeout: '3000'
cookies policy: 'compatibility', clear_each_iteration: true
#'cookies' is method defined under 'ruby-jmeter'
cache clear_each_iteration: true # 'cache' is method defined under
'ruby-jmeter'
# starting testPlan 'JiraAnalyticsPerformanceFlow'
test name:"testFlowName" do
adminwebservice = API::AdminWebService.new(self)
adminwebservice.get_space_properties(Payload.get_local_payload("get_space_properties.xml"))
#Payload is another common utility class for fetching payload stuff
end
puts "JMX FILE IS GONNA SAVED #
"+Dir.pwd+"/CreatedJMeter_DB2Navigation.jmx"
end.jmx(file: Dir.pwd+"/CreatedJMeter_DB2Navigation.jmx")

Issue with Shoes setup

When i am running shoes.rb file, which contains code to install gem, it throws error.
Undefined method setup for Shoes:Class
Code:
Shoes.setup do
gem 'activerecord' # install AR if not found
require 'active_record'
require 'fileutils'
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:dbfile => 'shoes_app'
)
# create the db if not found
unless File.exist?("shoes_app.sqlite3")
ActiveRecord::Schema.define do
create_table :notes do |t|
t.column :message, :string
end
end
end
end
class ShoesApp < Shoes
require 'note'
url '/', :index
def index
para 'Say something...'
flow do
#note = edit_line
button 'OK' do
Note.new(:message => #note.text).save
#note.text = ''
#result.replace get_notes
end
end
#result = para get_notes
end
def get_notes
messages = []
notes = Note.find(:all, :select => 'message')
notes.each do |foo|
messages << foo.message
end
out = messages.join("n")
end
end
Shoes.app :title => 'Notes', :width => 260, :height => 350
The problem was using Shoes4, where the setup method was unimplemented.
Shoes4 now implements Shoes.setup for backwards compatibility reasons but you don't really need it, so it doesn't do anything except for printing a warning that you should rather do gem install gem_name instead of using Shoes.setup.

How to Handle ActiveRecord Migrations in a Distributed Gem?

I am trying to write an app as a gem using ActiveRecord without Rails.
My problem is how to migrate a database already deployed by a user who will not have rake, etc. I have just distributed a schema.rb file and created the db from that. But now I want to allow users to update to a new gem and migrate their db.
I've looked at ActiveRecord::Migrator, but can't figure out how to use it.
For example, how would I tell ActiveRecord::Migrator to run all migrations up from whatever is the current_migration?
Anyone have any suggestions for how to go about this or a good reference?
After going at this fresh this morning I came up with the following which is working well:
module Byr
module Db
class << self
attr_accessor :config
attr_accessor :adapter
attr_accessor :db_name
end
def self.create_sqlite(config)
require 'sqlite3'
config = config.merge('database' => File.join(Byr.db_dir, config['database']))
ActiveRecord::Base.establish_connection(config)
end
def self.create_pg(config)
require 'pg'
# Connect to the postgres db to create the db
ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres',
'schema_search_path' => 'public'))
begin
result = ActiveRecord::Base.connection.create_database(config['database'])
rescue PG::Error, ActiveRecord::StatementInvalid => e
unless e.message =~ /already exists/
raise
end
end
true
end
def self.mysql_creation_options(config)
#charset = ENV['CHARSET'] || 'utf8'
#collation = ENV['COLLATION'] || 'utf8_unicode_ci'
{:charset => (config['charset'] || #charset), :collation => (config['collation'] || #collation)}
end
def self.create_mysql(config)
require 'mysql2'
error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
begin
ActiveRecord::Base.establish_connection(config.merge('database' => nil))
ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
ActiveRecord::Base.establish_connection(config)
rescue error_class => sqlerr
access_denied_error = 1045
if sqlerr.errno == access_denied_error
print "#{sqlerr.error}. \nPlease provide the root password for your mysql installation\n>"
root_password = $stdin.gets.strip
grant_statement = "GRANT ALL PRIVILEGES ON #{config['database']}.* " \
"TO '#{config['username']}'#'localhost' " \
"IDENTIFIED BY '#{config['password']}' WITH GRANT OPTION;"
ActiveRecord::Base.establish_connection(config.merge(
'database' => nil, 'username' => 'root', 'password' => root_password))
ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
ActiveRecord::Base.connection.execute grant_statement
ActiveRecord::Base.establish_connection(config)
else
Byr.warn sqlerr.error
Byr.warn "Couldn't create database for #{config.inspect}, charset: #{config['charset'] || #charset}, collation: #{config['collation'] || #collation}"
Byr.warn "(if you set the charset manually, make sure you have a matching collation)" if config['charset']
end
rescue ActiveRecord::StatementInvalid => e
ActiveRecord::Base.establish_connection(config)
end
end
def self.migrate
sys_migration_dir = File.join(Byr.install_dir, "db/migrate")
ActiveRecord::Migration.verbose = true
ActiveRecord::Migrator.migrate(sys_migration_dir)
end
def self.connected?
ActiveRecord::Base.connected? and
ActiveRecord::Base.connection_config[:adapter] == adapter
end
def self.disconnect
ActiveRecord::Base.connection_pool.disconnect!
end
# Really only for testing
def self.drop_db
ActiveRecord::Base.connection.drop_database(Byr.db_config)
end
end
end
Then, to initialize the db via the migrations:
module Byr
class << self
attr_accessor :install_dir
attr_accessor :db_dir
attr_accessor :config_dir
attr_accessor :config_file
attr_accessor :config
attr_accessor :db_config
attr_accessor :adapter
attr_accessor :database
def self.create_db
case db_config['adapter']
when /postgresql/
Byr::Db.create_pg(db_config)
when /sqlite/
Byr::Db.create_sqlite(db_config)
when /mysql/
Byr::Db.create_mysql(db_config)
else
raise ByrError "Your config.yml file specifies an unknown database adapter \'#{config['adapter']}\'"
end
end
def self.connect_db(reconnect = false)
unless reconnect
return true if Byr.connected?
end
ActiveRecord::Base.establish_connection(db_config)
end
def self.migrate
Byr::Db.migrate
end
def self.init(connect = true, adapter = nil)
adapter = canonicalize_adapter(adapter) if adapter
setup_db_config
if connect
create_db and connect_db and migrate
end
end
end
Some irrelevant parts of the code are omitted, but I hope this helps
someone else.
Much of the hard stuff comes from the rake tasks in rails.

Error generating test routes for Rails 3 plugin?

I'm trying to develop tests for plugin "foobar" that modifies some of the standard Rails helpers. In vendor/plugins/foobar/test/foobar_test.rb, I have the following:
# create the test model
class Thing < ActiveRecord::Base
end
# create the test controller, which renders the included index template
class ThingsController < ActionController::Base
def index
#things = Thing.all
format.html { render(:file => 'index') }
end
def destroy
#thing = Thing.find(params[:id])
#thing.destroy
format.html { render(:file => 'index') }
end
end
# confirm that the test environment is working correctly
class ThingsTest < ActiveSupport::TestCase
test "model is loaded correctly" do
assert_kind_of Thing, Thing.new
end
end
# confirm that the controller and routes are working correctly
class ThingsControllerTest < ActionController::TestCase
test "should load index" do
with_routing do |set|
set.draw do
resources :things, :only => [:index, :destroy]
end
get :index
assert_response :success
end
end
end
When I run rake, I get the following output:
test_should_load_index(ThingsControllerTest):
NameError: undefined local variable or method `_routes' for ThingsController:Class
Any idea what I'm doing wrong that is preventing me from accessing the routes? I've been at this for days and scoured much documentation, to no avail. Thanks for the help!
I got things to work on Rails 3.1.0.rc1 with Ruby 1.9.2, by following "The Basics of Creating Rails Plugins" Rails Guide and correcting the code whenever it exploded due to an incompatibility.
I started by running:
Code$ rails new tester
Code$ cd tester
tester$ rails generate plugin foobar --with-generator
Then modifying the generated code to obtain these files in addition to the default ones:
# vendor/plugins/foobar/init.rb
require 'foobar'
# vendor/plugins/foobar/lib/foobar.rb
%w{ models controllers helpers }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.autoload_paths << path
ActiveSupport::Dependencies.autoload_once_paths.delete(path)
end
# I'm not entirely sure this is the best way to add our plugin's views
# to the view search path, but it works
ActionController::Base.view_paths =
ActionController::Base.view_paths +
[ File.join(File.dirname(__FILE__), 'app', 'views') ]
<!-- vendor/plugins/foobar/lib/app/views/things/index.html.erb -->
<h1>Listing things</h1>
<table>
<tr>
<th>Name</th>
<th></th>
</tr>
<% #things.each do |thing| %>
<tr>
<td><%= thing.name %></td>
<td><%= link_to 'Destroy', thing, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
# vendor/plugins/foobar/test/database.yml
sqlite:
:adapter: sqlite
:dbfile: vendor/plugins/foobar/test/foobar_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:database: vendor/plugins/foobar/test/foobar_plugin.sqlite3.db
postgresql:
:adapter: postgresql
:username: postgres
:password: postgres
:database: foobar_plugin_test
:min_messages: ERROR
mysql:
:adapter: mysql
:host: localhost
:username: root
:password: password
:database: foobar_plugin_test
# vendor/plugins/foobar/test/schema.rb
ActiveRecord::Schema.define(:version => 0) do
create_table :things, :force => true do |t|
t.string :name
t.datetime :created_at
t.datetime :updated_at
end
end
# vendor/plugins/foobar/test/test_helper.rb
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
def load_schema
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init'
end
load_schema
# vendor/plugins/foobar/test/foobar_test.rb
require File.dirname(__FILE__) + '/test_helper'
# create the test model
class Thing < ActiveRecord::Base
end
# create the test controller, which renders the included index template
class ThingsController < ActionController::Base
def index
#things = Thing.all
respond_to do |format|
format.html # index.html.erb
end
end
def destroy
#thing = Thing.find(params[:id])
#thing.destroy
respond_to do |format|
format.html { redirect_to things_url }
end
end
end
# confirm that the test environment is working correctly
class ThingsTest < ActiveSupport::TestCase
test "schema has loaded correctly" do
assert_equal [], Thing.all
end
test "model is loaded correctly" do
assert_kind_of Thing, Thing.new
end
end
# confirm that the controller and routes are working correctly
class ThingsControllerTest < ActionController::TestCase
test "should load index" do
with_routing do |set|
set.draw do
resources :things, :only => [:index, :destroy]
end
get :index
assert_response :success
end
end
end
And finally, our test passes:
tester$ cd vendor/plugins/foobar/
foobar$ rake
-- create_table(:things, {:force=>true})
-> 0.0059s
-- initialize_schema_migrations_table()
-> 0.0002s
-- assume_migrated_upto_version(0, ["db/migrate"])
-> 0.0003s
Loaded suite /Users/nick/.rvm/gems/ruby-1.9.2-p0/gems/rake-0.9.2/lib/rake/rake_test_loader
Started
...
Finished in 0.091642 seconds.
3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
Your best bet for debugging this is to do
rake <task> --trace
This will give you a much better idea (i.e. a line number) on what is causing the _routes error.

Resources