Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Sunday, May 25, 2014

Share language files from a rails plugin

If you want to share you language file from with the plugin. Then you need to add the local files in the auto load path in the engine file like following,

Tuesday, March 11, 2014

Faster capistrano deploy with skipping bundler and asset precompilation

If you guys use git then you can use the following script in you deploy.rb to override the default behavior if asset pre compilation and bundle install.

Sunday, May 12, 2013

Readable model name with translation support

Use following to have the translated attribute with fallback support,
This will look in to the translation in the following order,
First it will look for the "en.activerecord.models.person.first_name" and then for "en.attributes.first_name" and finally falls back to humanize.

Sunday, May 5, 2013

Encapsulate views in rails

We always hear that we have to keep our code clean and DRY. But I feel that poor view files are always left out from this concern. We do not write html to support the change of DOM. Yes, true for rails we have layouts and partials. But these features some times is not enough for encapsulating views.
Let's say we are using jQuery UI in our application and we want to switch to twitter bootstrap :-S. Now that will be a pain, right? Because you have all sorts of views and DOM structures designed for jQuery UI. So for projects that we plan to maintain for a long time, we should consider to encapsulate almost every thing. Such as we can use unobtrusive Javascript to have the flexibility to switch between JS libraries. But in this post I plan to discuss the view layer and a particular mehod to encapsulate DOM and view logic.
People are already doing it. Rails form builders, simple form, active admin DSL can be some of the examples. Obviously we can use partials to reduce the duplication but here I am talking about dom structure.
So here is the pattern that is used by simple form or form builders, you might call it the builder pattern. Here is a simple example which will clear the cloud I think.

I would prefer to encapsulate the view with a DSL as following,
Here is the helper code to support the DSL.
And the target resulting dom is as follows.

The DSL is fairly simple actually. The two things you need to know before hand is how capture method works for rails template and that you have to pass the self as template so that later you can call the capture method using the template object. Any method that you can run from the view, you can run on template object.
As you can see for widget we I have used an object to as we need related sub blocks(title, content). You can also use the simpler version which is shown in header block. Usually form builders need the object reference as they have states. But for us widgets donot have states. Still it is a good way to go, because later you might have different type of widget and then, you might pass that as argument. In that case your widget will have state and the w object will help you to maintain that state. I hope that helps :)

References

Wednesday, May 23, 2012

Cucumber remove Rack::Cache logging

I am using a cucumber and capybara-webkit in a project that uses Dragonfly.
When I used capybara-webkit I suddenly started getting some Rack::Cache debug log. Which looked like the following,

 @javascript
  Scenario: Save new event as draft                               # features/manage_events.feature:23
cache: [GET /user/sign_out] miss
cache: [GET /] miss
cache: [POST /user/sign_in] invalidate, pass
cache: [GET /events/new] miss
http://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/8/11/%7Bmain,geometry%7D.js|43|Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
cache: [PUT /users/update_time_zone] invalidate, pass
cache: [GET /events/new] miss
http://maps.gstatic.com/cat_js/intl/en_us/mapfiles/api-3/8/11/%7Bmain,geometry%7D.js|43|Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
cache: [PUT /users/update_time_zone] invalidate, pass
    When I fill in "Event Name" with "Event 1"                    # features/step_definitions/web_steps.rb:3
    And I fill in "Event Description" with "This is a test event" # features/step_definitions/web_steps.rb:3
    And I fill in "Event Venue" with "Dhaka, Bangladesh"          # features/step_definitions/web_steps.rb:3
    And I press "Search"                                          # features/step_definitions/web_steps.rb:7
cache: [GET /events/location_search?str=Dhaka,%20Bangladesh] miss
    And I fill in "Event Start date" with "2012-05-22"            # features/step_definitions/web_steps.rb:3
    And I fill in "Event End date" with "2012-05-23"              # features/step_definitions/web_steps.rb:3
    And I press "Save as draft"                                   # features/step_definitions/web_steps.rb:7
cache: [POST /events/4fbc72688621ff1a31000026] invalidate, pass
cache: [GET /my/events?p=false] miss
cache: [GET /assets/ui-bg_glass_65_ffffff_1x400.png] miss
cache: [GET /assets/bg.gif] miss
    Then I should see "Event was successfully updated."           # features/step_definitions/web_steps.rb:11
That log comes from the Rack::Cache which is used by Dragonfly. So you can add the following code snippet in the test.rb,
  require 'rack/cache'
  config.middleware.delete ::Rack::Cache
  rack_cache_already_inserted = Rails.application.config.action_controller.perform_caching && Rails.application.config.action_dispatch.rack_cache

  Rails.application.middleware.insert 0, Rack::Cache, {
      :verbose => false,
      :metastore => URI.encode("file:#{Rails.root}/tmp/dragonfly/cache/meta"), # URI encoded in case of spaces
      :entitystore => URI.encode("file:#{Rails.root}/tmp/dragonfly/cache/body")
  } unless rack_cache_already_inserted



References

Tuesday, May 22, 2012

Cucumber on rails

The purpose of this document is the following

  • Setup cucumber with rails
  • Define basic features
  • To test ajax response
The version for gems that are used to create the documents are,
  • cucumber (1.2.0)
  • cucumber-rails (1.3.0)

Setup

Cucumber-rails gem makes it easier to install cucumber in rails, but I faced some issues which I would like to document. The following is from the cucumber-rails document,
group :test do
  gem 'cucumber-rails', :require => false
  # database_cleaner is not required, but highly recommended
  gem 'database_cleaner'
  gem 'cucumber-rails-training-wheels'
  gem 'capybara'
  gem 'rspec-expectations'
  gem 'fabrication' #for test fixture creation
end
Then run,
bundle install
rails generate cucumber:install
This will generate the necessary file for cucumber.
  create  config/cucumber.yml
  create  script/cucumber
   chmod  script/cucumber
  create  features/step_definitions
  create  features/support
  create  features/support/env.rb
   exist  lib/tasks
  create  lib/tasks/cucumber.rake
If you are using mongo, then it should give you a warning that you can not use 'transaction' strategy for mongo. Then you can change that to 'truncation' in your 'features/support/env.rb' file. Change the env.rb as following,
DatabaseCleaner.strategy = :truncation
Now it is time to write some features to test. cucumber-rails-training-wheels gem help you with generators, so that you can generate features quickly. To generate use the command as follows,
rails generate cucumber_rails_training_wheels:feature post title:string body:text number:integer published:boolean
With this plug-in you can generate cucumber feature when you are using scaffold generator. For details please see the reference.
I am working on a sample cucumber project that can facilitate newbies to get started with cucumber and get to know the best practices. Any contribution is very welcome.

Global fixture setup and tear down

If you have some global data that is needed to be loaded for every test then you can use cucumber hooks. You can create the fixtures that you always need, for an example users for login or initialize admin global settings.

Reference

Wednesday, May 2, 2012

Parameterizing translation files in rails I18n

In en.yml,

delete_confirm_with_title: 'Are you sure, you want to delete "%{title}"?'

In erb
<%= link_to 'X', resource, confirm: t('delete_confirm_with_title', {:title => resource.name}), method: :delete %>

Friday, March 9, 2012

Rails JSON mapping

Rails to_json is great when you are using web service to talk to your own application. But sometimes when you expose service for some third party application, then you need to export you own data in their format. In my can I had to expose my data to be able to use fullcalendar. And fullcalendar expects data in their format. So thanks to the discussion here, I found a way to represent your in the following way,

  def story_feed
    @stories = @project.stories
    render :json => @stories.map { |story| 
      { :id => story.id,
        :title => story.title,
        :start => story.start_at || Date.today,
        :end => story.complete_at || Date.today }
    }
  end

Monday, December 26, 2011

Customizing rails default generators

Objective

Customizing the template of default rails generators.

How it works


This is actually pretty simple :) You might get an idea when you take a look here. There you can find all the templates. Now if you want to customize lets say the index.html.erb, then in your project directory create the "lib/templates/erb/scaffold/index.html.erb". After that when you create a scaffold the generator will use your template.

Reference



Sunday, December 11, 2011

Project Portfolios engine for Refinery CMS

Just added a new kind of portfolio to get it running in RefineryCMS. Here is demo.
Project portfolio
Project details popup

Wednesday, June 16, 2010

Faqs plugin for Refinery CMS

Refinery is one of the rails CMS that allows people to extend the CMS and build custom plugin on that. The plugins are easy to include and maintain.
Faqs are one of the essential part for most of the web applications. So I build a plugin for refinery. The project is kept on github. Follow the following scripts to include the plugin.

script/plugin install git://github.com/ashrafuzzaman/refinerycms-faqs.git
rake refinery:faqs:install

Thursday, December 24, 2009

Implementing Payson API Integration 1.0 in Ruby

To do payment using Payson API integration 1.0 you need to follow 3 steps.
  1. Request to initiate a pay request (in return it will send you back a token)
  2. Redirect client to Payson site using that token
  3. After client completes the payment, Payson will redirect the client back to your site and you can check the payment status and update status of payment on your application
Payson api cycle

Plugin used

RestClient is nice API to handle http request and response.

Step 1 (Request to initiate a pay request)

To be able to use Payson API integration you must have,
AgentID: XXXX
MD5-key: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
For a pay initiate request you can see the specification here. Before you integrate the API in your application you can make a curl http call just to check if every thing works.
curl -H "PAYSON-SECURITY-USERID:XXXX" \
-H "PAYSON-SECURITY-PASSWORD:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" \
-d "receiverList.receiver(0).email=test@gmail.com&receiverList.receiver(0).amount=10&returnUrl=http://localhost:3000/payson_return/56&cancelUrl=http://localhost:3000/payson_cancel/56&memo=test&senderEmail=sender@gmail.com&senderFirstName=A.K.M.&senderLastName=Ashrafuzzaman" https://api.payson.se/1.0/Pay/ -o payson.out
Here PAYSON-SECURITY-USERID is AgentID and PAYSON-SECURITY-PASSWORD MD5-key. And as you can see PAYSON-SECURITY-USERID and PAYSON-SECURITY-PASSWORD (the authentication fields) will have to be send in the headers of the request. Now it should return a message which looks like,
responseEnvelope.ack=SUCCESS&responseEnvelope.timestamp=2009-11-15T17%3a14%3a03&responseEnvelope.version=1.0&TOKEN=4ecce14b-a4c7-4990-9814-db8aa2e97553
The response will contain a token which will be used to do the pay request.
Now let us see the ruby version of the curl request,
params_list = { 'receiverList.receiver(0).email' => reciever_email,
  'receiverList.receiver(0).amount' => recieving_amount,
  'receiverList.receiver(1).email' => more_receiver_email, #you can send money to more then one account
  'receiverList.receiver(1).amount' => more_receive_amount,
  'returnUrl' => callback_url,
  'cancelUrl' => cancel_url,
  'memo' => description,
  'senderEmail' => sender_email,
  'senderFirstName' => first_name,
  'senderLastName' => last_name }

header_list = {'PAYSON-SECURITY-USERID' => 'XXXX', 'PAYSON-SECURITY-PASSWORD' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'}

response = RestClient.post 'https://api.payson.se/1.0/Pay/', params_list, header_list

Step 2 (Redirect client to Payson site)

Now parse the response and redirect to Payson site for client to complete the payment.
response_hash = parse_response(response)

if response_hash['responseEnvelope.ack'] == 'SUCCESS'
  logger.info "Payson pay response #{response}"
  @signup.payson_token = response_hash['TOKEN']
  @signup.save!
  redirect_to "https://www.payson.se/PaySecure?token=#{response_hash['TOKEN']}"
elsif response_hash['responseEnvelope.ack'] == 'FAILURE'
  redirect_to @signup.event.home_path
end
This will redirect to Payson paysecure page. And client will complete the payment which will redirect the client back to returnUrl. If the client cancels the payment then he will be redirected to cancel url.

Step 3 (complete the process)

Now it is time to nail it ;)
In the return action you should check that the payment is done.
response = RestClient.get "https://api.payson.se/1.0/PaymentDetails?token=#{signup.payson_token}",
              {'PAYSON-SECURITY-USERID' => 'XXXX', 'PAYSON-SECURITY-PASSWORD' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'}
response_hash = parse_response(response)
@signup.payson_params = response_hash
@signup.payson_status = response_hash['responseEnvelope.status']
@signup.save!
if @signup.payson_status == Payment::PaysonClient::COMPLETED
  confirm_signup
else
  @signup.fail!
  ErrorNotifier.deliver_notification("Payment failed with status #{@signup.payson_status} for signup #{@signup.inspect}")
end
You can check the reference for pay details request here.

Thursday, August 6, 2009

Using acts_as_auditable for keeping history for model activities in rails

Keeping change history for important models are crucial for some application. And acts_as_auditable provides a clean implementation for keeping history.

Install

1. Download acts_as_auditable and put in your vendor folder

2. run

ruby script\generate audit

from your application directory. Which will generate a migration script to create audits table and a model named Audit.

Expectation

1. User model that inherits from ActiveRecord::Base with an instance method of auditor_name(it is required as it stores the auditors name as well as the auditor’s reference for keeping history).

2. A property named auditor(which will be injected in the model where you are using audit) should be prefilled with the user object who is changing the model.

3. Now you can use audit in your model as,

audit :when => :before_update,
      :if => lambda {|work_item| work_item.changed? },
      :with_message => lambda { |post| 'Something changed :)' }

Here

:when         => any active record callbacks (like :before_create)
:if           => provide a condition which will be checked to create the audit
:with_message => the message to be stored

Well that’s about it to use acts_as_auditable.

Implementing in real project

The challenge that I faced is to create a human readable message for model and make it maintainable.

I actually used audit like,

audit :when => :before_update,
      :if => lambda {|work_item| work_item.changed? },
      :with_message => lambda { |work_item| work_item.audit_message }

Now here is the code to generate the message.

def audit_message
  history_text = ''
  self.changes.each do |field, change|
    history_text += "#{field.humanize} changed from '#{change[0]}' to '#{change[1]}'\n" unless field.ends_with?('_id')
  end

  history_text += audit_message_for('project_id', Project, :name, 'project')
  history_text += audit_message_for('sprint_id', Sprint, :name, 'sprint')
  history_text += audit_message_for('responsible_person_id', User, :full_name, 'responsible_person', 'Responsible Person')
  history_text += audit_message_for('release_id', Release, :name, 'release')
  history_text += audit_message_for('point_id', Point, :name, 'point')

  return history_text
end

And here is the nasty part that at least cleans the audit message implementation. It helps to generate audit message for reference objects.

private
# Used for making the audit text readable
#
# ==== Parameters
#
# * +field+ - The database field to inspect changes
# * +klass+ - The class for the referenced object
# * +klass_property+ - The property of the object which will be readable to store audit data
# * +readable_name+ - readable name for the class. By default it is klass.to_s
#
# ==== Returns
# The audit text for that field.
# If there is no change in the field then empty string is returned
def audit_message_for(field, klass, klass_property, belongs_to, readable_name = klass.to_s)
  history_text = ''
  seperator = '\n'
  #as this is done with reflaction, catching exeptions for protection
  begin
    if self.send("#{field}_changed?")
      field_was = "#{field}_was"

      changed_from = klass.find(self.send(field_was)).send(klass_property) unless self.send(field_was) == nil
      changed_to   = self.send(belongs_to).send(klass_property) unless self.send(field) == nil

      if self.send(field_was) == nil
        history_text = "#{readable_name} assigned to '#{changed_to}'#{seperator}"
      elsif self.send(field) == nil
        history_text = "Removed #{readable_name} from '#{changed_from}'#{seperator}"
      else
        history_text = "#{readable_name} changed from '#{changed_from}' to '#{changed_to}'#{seperator}"
      end
    end
  rescue Exception => ex
    logger.error "Error #{ex.to_s}"
  end

  return history_text
end

Another thing to consider is assigning the auditor before saving the history. It is cleaner if you define a method named auditor. That is how you can avoid assigning to that attribute.

def auditor
  return self.new_record? ? self.creator : self.updator
end

But for implementing like this you need to modify some code in the library. Open the vendor\plugins\acts_as_auditable\lib\shooter\acts\auditable.rb and remove the line,

attr_accessor :auditor

Otherwise your method will be overwritten.

Thursday, July 23, 2009

Looking into rails named_scope

named scope?

Nick Kallen’s has_finder plugin has found it’s way into rails 2.x as named_scope. Named scope is all about scoping or narrowing the database query.

Let me go through an example to make things easy.

class Post < ActiveRecord::Base
  belongs_to :author,   :class_name => 'User'
  has_many   :comments, :dependent  => :destroy

  named_scope :published,   :conditions => { :is_published => true }
  named_scope :draft,       :conditions => { :is_published => false }
  named_scope :has_comment, :conditions => [ 'comments_count > 0' ]

  named_scope :recent,    lambda { |*date| {:conditions => { :created_at => date.first || 1.weeks.ago } } }
  named_scope :before,    lambda{ |date| { :conditions => ['created_at > ?',  date] } }
end
You can scope your query and make it more readable.
Post.published #equivalant to Post.all.published

You can also scope on finder methods like,

Post.find(:all, :conditions => { :created_at => 1.weeks.ago }).published

You can use finder on scope like,

Post.published.find(:all, :conditions => { :created_at => 1.weeks.ago })

Even scope on the relations.

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :author, :class_name => 'User'

  named_scope :unread, :conditions => {:is_unread => true}
  named_scope :read, :conditions => {:is_unread => false}
end

So now you can write like,

Post.find(id).comments.unread

Chaining

Now would not it be wonderful if you could write like “Get all posts which are recently published” and it would return you what it means.

Using named_scope that dream will come true ;). You can finally write code like this,

Post.recent.published

You can chain up to your hearts content ;). You can do all sort of combination like,

Post.recent.published.has_comment

Which will return you posts which are recently published and has comments. See how much readable the code has become.

Passing Arguments

You can pass arguments using lambda.

Post.published.before(1.days.ago)

Named Scope Extensions

Extend named scope and add methods to it.

class Post < ActiveRecord::Base
  named_scope :draft,       :conditions => { :is_published => false } do
    def publish
      each { |post| post.update_attribute(:is_published, true) }
    end
  end
end
Post.recent.draft.publish

This will find all recent draft posts and publish them.

Anonymous Scopes

Creating named scopes on the fly.

# Store named scopes
published = Post.scoped(:conditions => { :is_published => true })
recent    = Post.scoped(:conditions => { :created_at => 1.weeks.ago })

# Which can be combined
recent_published = recent.published

Why use named scope?

  • Increases readability
  • Reduces number of queries as it can be chained
  • Very helpful for dynamic queries(like using pagination or dynamic filter)

A common issue

Named scope is a class methods. And you should always be very careful for class methods. Here is an example where most people does it wrong.

class Post < ActiveRecord::Base
  belongs_to :author,   :class_name => 'User'
  has_many   :comments, :dependent  => :destroy
  
  named_scope :recent,  :conditions => { :created_at => 1.weeks.ago } 
end

Now I can call Post.recent and expect to get all Posts within one week. But in times you will find that this query is starting to give wrong results.

Why???!!!

Named scope is a class method and so 1.weeks.ago is evaluated when the class was loaded. Now it does not matter when you call the named scope it will always run the query with the same created_at date. We also made this mistake :( and learned from it :)

A lambda block is not evaluated when the class is loaded. So there is a work around it.

class Post < ActiveRecord::Base
  belongs_to :author,   :class_name => 'User'
  has_many   :comments, :dependent  => :destroy

  named_scope :recent,    lambda { |*date| {:conditions => { :created_at => date.first || 1.weeks.ago } } }
end

Taking the lambda input like this will give you flexibility of not providing the parameter at all. For now ruby does not provide facility to take default parameter for lambda.

Deep inside named scope

The implementation of Named scope is a beauty of rails. Although the result that named scope produces seems like an Array, but actually it is not an Array but a simulation of an Array. Calling a named scope over a finder object actually returns a ActiveRecord:NamedScope:Scope object. When we chain scopes on that object, appends the query logic in the scope object. The query is not evaluated until an Array method(like each, first, last) etc is called. And when these Array methods are called the scope object then evaluates the query and delegates the method which was called as an array to the real array that has been evaluated. Now you can not chain the scope any more, as it is already been evaluated. That is how the named scope magic works in ruby on rails.

Reference

http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality

http://railscasts.com/episodes/108-named-scope

http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/named_scope

Thursday, July 9, 2009

Rails logger configuration and log level in production environment

In production environment, it not feasible to use one log file forever. So people use log that rolls over, depending on file size or time etc.

If we want to roll over the log file, we can define our custom logger using the following code in the configuration(in config/environments/production.rb).

config.logger = Logger.new(config.log_path, 50, 5242880)
Here is the doc for instantiating Logger. The params are as follows.
Logger.new(name, shift_age = 7, shift_size = 1048576)<br />Logger.new(name, shift_age = 'weekly')
Another thing that we need to set for the production is the log level. We do not need to log the query generated by active record or logs that are in debug level. So we can define the log level as follows.
config.logger = Logger.new(config.log_path, 50, 5242880)<br />config.logger.level = Logger::INFO
But if you are using the default log which rails offers by default, you can set the log level as,
config.log_level = :info
You can find the rails environment configuration cheat sheet here.

Wednesday, July 8, 2009

Some of the useful way of using fixture better

1. Using new fixture facilities in rails 2.(example)

    Which will remove the relational fixtures for has_many :through and has_and_belongs_to_many relations.

    It will remove the ids and will give a better way of relating between tables.

2. Fixtures are read only:    Never modify any existing fixture, unless your database schema has changed.    Which also indicates that we should be very careful when are adding a new fixture.

3. Another way to identify if the fixture is well written is that they all should be meaningful.    And none of them should look similar.

   If a different fixture is needed for only 1 or 2 test, then update existing before doing the test.    For an example,

should 'assign responsible person to unassigned task' do
    task = tasks(:task_not_started)
    task.users.clear #clear the existing fixture(not creating a new one for that fixture) 

    assign_and_assert_responsible_person(task, users(:login_user))
end
This will reduce the number of fixture set and keep them clean.

4. Often we write test codes that involves a lot of fixture.    Some times when we get test fail, we run through the fixtures, trying to find out which went wrong.    But instead if we comment our code such a way that the fixture is understood from the test code,    then that would be even better. Like,

context 'in progress task' do
  setup do
    @task = tasks(:task_in_progress)
    # task -> time_estimates
    #         [ user: login_user, hours_spent: 2, hours_remaining: 8, entry_date: 1.days.ago ]
    #         [ user: developer , hours_spent: 4, hours_remaining: 3, entry_date: Date.today ]
  end

  should 'return hours spent upto' do
    assert_equal(2, @task.hours_spent_upto(1.days.ago))
    assert_equal(6, @task.hours_spent_upto(Date.today))
  end
end
5. Inherit fields, that are less likely to be different for each fixture
backlog_item: &common_backlog_fields
  project_id: scrumpad
  type: Story

bug:
  <<: *common_backlog_fields
  type: Bug
  title: Test Bug
  content: Bug content
  created_at: <%= 10.days.ago.to_s(:db) %>
  updated_at: <%= 3.days.ago.to_s(:db) %>

story:
  <<: *common_backlog_fields
  title: Sample story
  state: <%= WorkItem::COMPLETED %>
  created_at: <%= 10.days.ago.to_s(:db) %>
  updated_at: <%= 2.days.ago.to_s(:db) %>
Here we can define the common required fields in backlog_item and use that definition for other fixtures. The fields can be overwritten by redefining in the fixtures as we did overwritten type for bug.

Friday, May 22, 2009

Selenium In Rails with Fixtures

Selenium is a framework for acceptance testing, designed for web applications. With selenium you can run your tests on all popular browsers.

Now a days web applications are consist of a lot of UI logic, animations, ajax calls. Only unit test and functional test does not ensure the stability of your application any more. A small change in Javascript can cause instability in your application. Tiny changes can break the contract of browser compatibility. A simple miss spelled link can give you a nightmare.

Selenium gives you the power to run automated acceptance test codes in real browsers. As it supports all popular browsers you can easily test browser compatibility of your application.

Key Features

  • Selenium IDE provides facility to record test script with ease and export the script to your preferred language(Java, C#, ruby, Perl, PHP etc)
  • Write one test script and run in all popular browsers and OS
  • Selenium Grid facilitates to run test codes parallely in multiple server, which pace up the execution of test code.

Setup

Install Selenium client

gem install selenium-client

Download Selenium Remote Control from here.

You will need Java installed on your machine to run Selenium Remote Control.

I write a script to start Selenium Remote Control, which is like.

cd E:\selenium\selenium-remote-control-1.0-beta-2\selenium-server-1.0-beta-2
java -jar selenium-server.jar

Use Firefox and Selenium IDE(a Firefox plugin) to capture the actions and convert it to ruby code.

XPath Checker and Fire Finder are two useful Firefox plugin to find and locate elements using xpath.

Record actions

Start Firefox, go to the root url, from where you are going to start test. Go to tools tab and start Selenium IDE.

Now as you browse through the site Selenium IDE will record the actions. After you have finished a scenario, you can stop recording and export test case as ruby file from File menu.

Selenium IDE generates is an old rails style code and it uses old selenium client driver. Here is a sample integration code that uses rails 2.3.2 style and new selenium client driver.Now to run your test code as you have noticed, you need mention the root url of the site you are testing.

require 'test_helper'
require 'selenium/client'

class PostsIntegrationTest < ActionController::IntegrationTest
fixtures :all

def setup
@browser = Selenium::Client::Driver.new(
:host => "localhost",
:port => 4444,
:browser => "*firefox",
:url => "http://localhost:3000",
:timeout_in_second => 60
)

@browser.start_new_browser_session
end

def teardown
@browser.close_current_browser_session
end

test 'the truth' do
@browser.open "/posts"
@browser.click "link=New post", :wait_for => :page
@browser.type "post_title", "test"
@browser.type "post_title", "Testing with Selenium"
@browser.type "post_body", "bla... bla..."
@browser.click "post_published"
@browser.click "post_submit", :wait_for => :page
assert_equal "Testing with Selenium", @browser.get_text("xpath=/html/body/p[2]/span")
end

end
Here is the trick. Run your application in test environment. So the application will use test database. As test database is prepared automatically by rails, you can use the test fixtures as the input set of you test codes. And it will be automatically reset to the fixture set for each test methods.

How to organize

1. Dry and reuse

Acceptance test codes are directly dependent on view code. So you need to reuse test codes as much as possible. If you don’t a simple change in view will make you life hell.

2. Separate your actions to methods, so that you can reuse

def login(user_name, password)
@browser.open "/"
@browser.type "user_name", user_name
@browser.type "password", password
@browser.click "css=.btn[name='commit']", :wait_for => :page
end

def login_as_developer()
login(users(:developer).user_name, '123')
end

Now you can call login method to login to the system. And do not put assertions in these methods. This way you can even test the failure path.

3. Now call these basic methods and do assertion. This will make your code readable.

test 'login as a developer with valid credential' do
login_as_developer()
assert_url('/dashboard/show')
end

Note: Well there is no such thing as assert_url in selenium client to assert the current relative url.You can copy the following code and put it in your test helper.

def assert_url(url)
assert_equal(url, @browser.get_location().match(/.+\/\/[^\/]+(.*)/)[1])
end

4. Use a different helper file for common methods. Don’t use the common test helper, as selenium test are quit different from unit and functional test of rails.

It does not uses mock request and response. So you can not use selenium methods else where. That is why it is better to separate the selenium test helper.

5. Use selenium-client, so that you can use different wait_for methods, which are very useful. See the documentation here.

Tuesday, May 12, 2009

A solution for a gem install mysql problem

Some times we get an error in linux as follows while running gem install mysql,

root@ip-10-251-30-82:/etc/mysql# gem install mysql
Building native extensions.  This could take a while...
ERROR:  Error installing mysql:
     ERROR: Failed to build gem native extension.

/usr/bin/ruby1.8 extconf.rb install mysql
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... yes
checking for mysql_query() in -lmysqlclient... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
     --with-opt-dir
     --without-opt-dir
     --with-opt-include
     --without-opt-include=${opt-dir}/include
     --with-opt-lib
     --without-opt-lib=${opt-dir}/lib
     --with-make-prog
     --without-make-prog
     --srcdir=.
     --curdir
     --ruby=/usr/bin/ruby1.8
     --with-mysql-config
     --without-mysql-config
     --with-mysql-dir
     --without-mysql-dir
     --with-mysql-include
     --without-mysql-include=${mysql-dir}/include
     --with-mysql-lib
     --without-mysql-lib=${mysql-dir}/lib
     --with-mysqlclientlib
     --without-mysqlclientlib
     --with-mlib
     --without-mlib
     --with-mysqlclientlib
     --without-mysqlclientlib
     --with-zlib
     --without-zlib
     --with-mysqlclientlib
     --without-mysqlclientlib
     --with-socketlib
     --without-socketlib
     --with-mysqlclientlib
     --without-mysqlclientlib
     --with-nsllib
     --without-nsllib
     --with-mysqlclientlib
     --without-mysqlclientlib


Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.7 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/mysql-2.7/gem_make.out
root@ip-10-251-30-82:/etc/mysql# gem install mysql -- --with-mysql-config=/etc/mysql/my.cnf
Building native extensions.  This could take a while...
ERROR:  Error installing mysql:
     ERROR: Failed to build gem native extension.

The solution is simple :)

Just run,

apt-get install libmysqlclient15-dev libmysqlclient15off zlib1g-dev libmysql-ruby1.8

Run the following if you do not have mysql installed,

apt-get install mysql-server-5.0 mysql-client-5.0 libmysqlclient15-dev libmysqlclient15off zlib1g-dev libmysql-ruby1.8

And then run

gem install mysql

Saturday, May 2, 2009

Testing model in rails

How we want our test environment

  1. Isolation of input fixtures, so that changing fixture of one test code will not impact others.
  2. Easily create input set and reuse existing.
  3. Readable test code.
  4. Runs very fast(Slower test codes are run less by developers).
  5. Write less to test.

Problems with built in fixture and test helper

  1. Fixture does not allow to isolate input set.
  2. No feature of reusability in fixtures causes developer to create unnecessary duplication in fixtures.
  3. Changes in table definition causes a lot of change in fixture set.
  4. Fixtures are hidden in different file. So it becomes difficult to trace a test code.
  5. Fixture is database driven. So even if you do not need a saved instance of an ActiveRecord object, you end up using one. The more the queries get executed, the slower the test code becomes.

Factory girl, one of the alternate of fixture seems to be the better solution then fixture. And shoulda makes the life easier for writing test codes.

Why factory?

  1. Isolated input set
  2. Different build method gives the flexibility to create saved and unsaved instances
  3. Can easily extend existing factory to create a new one
  4. Facility to override property and to stub methods to reduce database query
  5. Increase readability of test codes.

Why Shoulda?

  1. Context & Should blocks - Context and should block provides facilities to do BDD
  2. Assertions - Provides many common and useful assertions
  3. Macros - Generate many ActionController and ActiveRecord tests with helpful error messages

So let’s get some action. Here is a simple test done using factory and shoulda. We will write unit test for User model which looks like the following.

class User < ActiveRecord::Base
 has_many :posts, :order => 'created_at DESC'
 has_many :comments

 validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
 validates_uniqueness_of :email

 def display_name
   return "#{first_name} #{last_name}"
 end

 def latest_post
   return self.posts.first
 end
end

The Post model is,

class Post < ActiveRecord::Base
 belongs_to :user
 has_many :comments, :dependent => :destroy

 validates_presence_of :title
 validates_presence_of :body
end

And the user factory is,

Factory.sequence :email do |n|
 "email#{n}@test.com"
end

Factory.define :user do |u|
 u.first_name 'Ashraf'
 u.last_name  'Zaman'
 #allows you to create different users with different email using the same definition
 u.email { Factory.next(:email) }
end

Post factory is,

Factory.define :post do |p|
 p.title 'A sample post'
 p.body  'This is a sample post'
 p.created_at Time.now
 p.updated_at Time.now
end

Finally the user model test is,

require 'test_helper'

class UserTest < ActiveSupport::TestCase

 should_have_many :posts
 should_have_many :comments
 should_require_unique_attributes :email

 should_not_allow_values_for :email, "ab.cd", "1234@"
 should_allow_values_for :email, "ashrafuzzaman.g2@gmail.com"

 should 'display_name' do
   user = Factory.build(:user, :first_name => 'Ashraf', :last_name => 'Zaman')
   assert_equal('Ashraf Zaman', user.display_name)
 end

 context 'Default posts' do
   setup do
     @user = Factory.build(:user, :posts => [
         Factory.build(:post, :title => 'Second Post', :created_at => Time.now),
         Factory.build(:post, :title => 'First Post', :created_at => 2.minutes.ago)
       ])
   end

   should 'return latest post' do
     assert_equal('Second Post', @user.latest_post.title)
   end
 end

end

You can download the demo from here

How factory helped

To test the display_name I do not need a saved instance, So I used Factory.build to build the model object with out saving it in the database.

Note: With Factory.build you can create an unsaved model instance from the factory prototype. It is very useful for testing model logic.

Some attributes of user prototype are intentionally redefined to increase the readability of the test code. Now you can easily read the test code as you can see the input set right in front of you. Thus you can effortlessly create different input set from one basic prototype.

The interesting part of this section is the test of latest_post of user model. Here as you can see the association method ‘posts’ is overridden with expected post list. Now you can mock this this methods as this is provided by the framework itself. So no need to test it. But by mocking this you actually increased the readability of the test code and avoided database call.

How shoulda helped

The Shoulda gem makes it easy to write elegant, understandable, and maintainable Ruby tests. Shoulda consists of test macros, assertions, and helpers added on to the Test::Unit framework.

With shoulda we defined a context 'Default posts' and initialized it. We can test codes related to posts with in the context. As the context is setup with the minimum and sufficient information of input set needed for the context, the test code becomes very simple and easy to read and maintain.

Resources

http://thoughtbot.com/projects/factory_girl

http://thoughtbot.com/projects/shoulda

Monday, April 27, 2009

Using webrat for integration testing

What is webrat

Webrat lets you quickly write expressive and robust acceptance tests for a rails application.

How Webrat is different from default rails integration test

1. Rails default integration testing is nothing more than a series of functional tests. But in webrat you can actually do actions in pages. Here is a scenario for login.

visit('/')
fill_in('email', :with => user.email)
fill_in('password', :with => '1234')
click_button('login')

2. With webrat you can test user experience by filling in the text boxes, clicking the buttons etc.

3. Use webrat API for Browser Simulator and real Selenium tests using Webrat::Selenium when necessary (eg. for testing AJAX interactions).

4. Supports popular test frameworks: RSpec, Cucumber, Test::Unit and Shoulda

Installing webrat

gem install nokogiri
gem install webrat

In test_helper.rb add,

require "webrat"

Webrat.configure do |config|
 config.mode = :rails
end

For more information please visit http://github.com/brynary/webrat/tree/master

Some Tips

You can check something like, if your desired dropdown select option is currently selected or not using assert_select.

Let me show you the expected html to test

<select name="user[user_type_id]" id="user_user_type_id">
 <option selected="selected" value="1">Shipper</option>
 <option value="2">Transporter</option>
</select>

Here we want to test of Shipper is selected or not.

So the test code can be

test 'signup form with shipper' do
 visit('/')
 click_link('Signup as Shipper')
 assert_selected_option('user_user_type_id', 'Shipper')
end

def assert_selected_option(select_id, selected_text)
 assert_select("##{select_id} option[selected=selected]", selected_text)
end

This is how you can test contents of html.

Resources

http://github.com/brynary/webrat/tree/master

http://www.slideshare.net/brynary/webrat-rails-acceptance-testing-evolved

http://cheat.errtheblog.com/s/webrat/