Monday, July 16, 2012

Modules in Ruby - an overview

We can define any number of methods in a module. It simply holds all the defined methods and we can include/extend it in any class.
If you want to use all module methods access by an instance then include the module in that class.
If you want to use all module methods access by an class then extend the module in that class.
module Foo
  def foo
    puts 'foo called!'

class Bar
  include Foo
end # foo called! # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end # foo called! # NoMethodError: undefined method ‘foo’ for #

Hope this helps. Happy learning & coding :)

Tuesday, February 28, 2012

Rails 3.1.0 - functional/integration test to test AJAX

Integration test with ajax achieved by means of calling xhr like below
xhr :req_method, :path, :parameters, :headers

xhr :get, '/users/new' # new user action

xhr :delete, '/users/20' # delete user

In integration test, you need to specify full path to make it work.

Incase of Functional test, we can simply specify the name of action.


Authlogic login access in rails functional test

We are shifted to use Authlogic, Devise rather than rails authorization plugin/gem. We can do Integration with detailed explanations/tutorials available for Authlogic.

In Rails test (functional/integration test in particular), we are in need to test whether the user is logged-in or not.
To start testing the user session, we need to use authlogic session. By using the following steps we can access Authlogic session in our rails test

- Add the following line in your test_helper.rb
require "authlogic/test_case"

- And add the method in your test_helper.rb
def user_login(user)
UserSession.create(user ? user : nil)

- Then inside your functional/integration test file
Add this to top of all test
setup :activate_authlogic

- Logged in with any existing user

You are logged in.
- User session is accessible.

Web application testing is much easier in Rails :)


Run ruby script as a background process in windows

Hi Ruby folks,

I went across a scenario in need of running a ruby process in background particularly in Windows OS(in Unix based system we can use '&' to run any process/job in background).

To run any ruby program in background, do the following

- Take a copy of the file, which you needs to run.
- Save the file as .rbw extension.
- Use the command
start "Your job description" ruby D:\Ruby\Jobs\particular_job.rbw

- Once it started running, You got a new console window with the given message on top and process status in console.


Thursday, October 20, 2011


Integrating SOLR search into our application. “acts_as_solr” is the name of the plugin(also available as gem).
Install plugin:
script/plugin install git://

Install gem:
gem install acts_as_solr

Add the below line into your application's configuration file
config.gem "acts_as_solr"

Add this at the end of your Rakefile(only for using gem)
require 'aas_tasks'

After installing gem/plugin, following rake tasks are available to use
rake solr:destroy_index # Remove Solr index
rake solr:reindex # Reindexes data for all ac
ts_as_solr models.
rake solr:start # Starts Solr.
rake solr:stop # Stops Solr.
We can start, stop, reindex, destroy index by using the mentioned rake tasks.

Add the following rake task inside the solr rake file(gems/acts_as_solr/lib/tasks/solr.rake), to start solr in Windows environment.
desc "Starts Solr. on windows . Options accepted: RAILS_ENV=your_env, PORT=XX. Defaults to development if none."
task :start_win do
require "#{File.dirname(__FILE__)}/../../config/solr_environment.rb"
n ='localhost', SOLR_PORT)

rescue Net::HTTPServerException #responding
puts "Port #{SOLR_PORT} in use" and return

rescue Errno::ECONNREFUSED #not responding
Dir.chdir(SOLR_PATH) do
exec "java{ENV['RAILS_ENV']} -Djetty.port=#{SOLR_PORT} -jar start.jar"
puts "#{ENV['RAILS_ENV']} Solr started sucessfuly on #{SOLR_PORT}, pid: #{pid}."

Steps to configure solr in our application

1) Starts the solr server
rake solr:start

2) Changes to ActiveRecord model
acts_as_solr - all fields are indexed
class News < ActiveRecord::Base
acts_as_solr :fields => [:title, :content]

– specified fields are indexed
We can specify the name of the fields to be used for searching.
:if => we can supply any condition as string, proc, symbol, method. It will index the record only if condition returns true.

3) Do index/reindex
rake solr:reindex

4) Changes to Controller

query => query is a string representing your query

There are many options available in solr, we can do a refined search by using SOLR.

I faced one problem, acts_as_solr :if option is not working with rake task to reindex data. Instead of checking the condition it will simply indexes all the records. But other method like solr_save() checks the condition passed with acts_as_solr definition in model. I have added a patch to check the condition in rake task 'reindex'.

file path: acts_as_solr\lib\class_methods.rb
line no: 200 - 250
method name: rebuild_solr_index
Instead of normal collect,
items.collect! { |content| content.to_solr_doc }

We can use the following code, to filter the records with the condition defined in model and collect the remaining results
items = { |content| content.evaluate_condition_public(content)}
items.collect! { |content| content.to_solr_doc }

After doing the above changes, you can have a correct data in your search results. This is applicable only when we are using acts_as_solr with conditions in model.

acts_as_solr :fields => ["name","description"], :if => proc{|record|}

Hope, this is useful for someone who is using acts_as_solr with :if option.


Thursday, August 18, 2011

Functional Testing in Rails(to test Html)

Hi all,

I have used listed out some uses of assert_tag in Rails functional test. In many case, we need to test the html content of page like checkbox is checked or not, text fields holds correct value, drop down selected with correct option. For those kind of needs, we need to go for assert_tag. Below are the example usage of assert_tag in functional testing.

In Rails html testing, assert_tag method plays an vital role. Following are some of the ways to use assert_tag method

Get links inside div

assert_select "div#divID" do
assert_select "a[href=?]", "/path/to/some/page"

Check the content of any html element(here is an example for Div)

by className
assert_select "div.className", "Page Heading or content inside the div"
by element ID
assert_select "div#elementId", "Page Heading or content inside the div"

Check how many times any DOM element appears on the page:

In the below example, we tested how many number of user images loaded on the page
assert_select "div.className table tr td.userImage img", {:count => 4}

Presence of Textbox:

assert_tag "input", :attributes => {:id => "user_screen_name", :size => "30", :type => "text"}

Get value of Dropdown:

option = css_select("select#elementId option[selected='selected']")[0]
assert_equal "public", option['value'].to_s

Code with testcase improves the quality of code and at the sametime reduces the errors. Keep writing test for each line of code.

Monday, April 18, 2011

Alternative to "grep" command in Windows

Hi all,

I have shifted from ubuntu and started using windowsXP. When I tried to use the grep command in windows, it throws the error

Instead of using grep, we can use find
gem list|find "rails"

rails (3.0.10)