Ruby On Rails Integration Testing With Minitest And Capybara

Hi Guys! I am back again with one more article about ruby on rails.

I hope this is the right time to share one of my technical stuffs on ruby on rails after sharing PHP and Mobile stuffs.

Minitest And Capybara: Integration Testing Demystified

In this article, I am going to share my own experience and ideas of ruby on rails integration testing using Minitest and Capybara and tell you the process how it serves as one of the most preferred alternative for controller test.

Never miss an update from us. Join 10,000+ marketers and leaders.

A lot of you must have heard about Capybara but still for those who are new to this –

Capybara:

Capybara is an acceptance test framework used for web applications and supports developers in integration testing of Ruby on Rails applications with Minitest.

So, let’s get into the details about Capybara, Minitest and Integration Testing

Minitest:

Minitest is the default and a complete testing suite for Ruby application, which supports ancillary test-driven development (TDD), behavior-driven development (BDD), mocking, and benchmarking for fast, clean and reliable test results.

Whereas, Capybara is the acceptance test framework for web applications and frequently used for end-to-end testing in Rails Applications.

Rails developer can suggest user on web page and Capybara provides API to interact with web page.

Integration Testing: 

Integration Testing are used to test the most important workflows of applications and test different fragments of application together while unit testing inspects the individual part of the application work.

Before sharing the real process how to use Capybara with Minitest for integration testing of your Ruby on Rails applications, let me tell you the prerequisites of this testing process.

Ruby version 2.3.3, Rails version 5.0.0.1,
Minitest version 5.10.1, and Capybara version 2.11.1 are required for the smooth operation and you can use gem install rails to get started.

Setup

You can set up a new Rails application.

rails new integration-testing-minitest

We’ll need to add Capybara to our – Gemfile

in the group test.

[code language=”php”]# Gemfile

group :test do
gem ‘minitest-rails-capybara’
end
[/code]

Also need to load Capybara in order to use it in our tests.

[code language=”php”]
# test/test_helper.rb

ENV[‘RAILS_ENV’] ||= ‘test’
requireFile.expand_path(‘../../config/environment’, __FILE__)
require ‘rails/test_help’
require "minitest/rails/capybara"

[/code]

Now, that you have everything set up, let’s see the integration tests with an example application.

Running the scaffold generator to create posts.

[code language=”php”]
rails generate scaffold Post title:string body:text
[/code]

Next we need to migrate the database.

[code language=”php”]
rake db:migrate
== 20161214213527 CreatePosts: migrating ======================================
— create_table(:posts)
-> 0.0020s
== 20161214213527 CreatePosts: migrated (0.0024s) =============================
rake
# Running:
…….
[/code]

You can also issue

[code language=”php”]rails server[/code]

at the command line and navigate to http://localhost:3000/posts to check the result.

Integration Tests

 Let’s create our first integration test.

[code language=”php”]
# test/fixtures/posts.yml

one:
title: Post Title One
body: Post body one.

two:
title: Post Title Two
body: Post body two.
[/code]

Here’s our first integration test.

[code language=”php”]
# test/integration/post_flow_test.rb

require ‘test_helper’

classPostFlowTest> Capybara::Rails::TestCase
def setup
@one = posts :one
@two = posts :two
end

test ‘post index’ do
visitposts_path

assertpage.has_content?(@one.title)
assertpage.has_content?(@two.title)
end
end
[/code]

All you need to do here is – to run all your tests again to make sure they all pass

[code language=”php”]
rake
# Running:
……..
Finished in 0.515325s, 15.5242 runs/s, 21.3458 assertions/s.

8 runs, 11 assertions, 0 failures, 0 errors, 0 skips
[/code]

Now, let’s move on to something a bit more complicated, and test if you can write a new post and submit it. Place it below other test in your integration test for posts.

[code language=”php”]
# test/integration/post_flow_test.rb

test ‘writing a new post’ do
visitposts_path

click_on ‘New Post’

fill_in ‘Title’, with: ‘Test Title’
fill_in ‘Body’,  with: ‘Test Body’

click_on ‘Create Post’

assert_current_pathpost_path(Post.last)
assertpage.has_content?(‘Test Title’)
assertpage.has_content?(‘Test Body’)
end
end
[/code]

Run the tests again to make sure everything passes.

[code language=”php”]
rake

# Running:

………

Finished in 0.551475s, 16.3199 runs/s, 23.5731 assertions/s.

9 runs, 13 assertions, 0 failures, 0 errors, 0 skips
[/code]

Now, we have one last feature to add, the email alert to an admin email once a post has been submitted. Let’s start by adding a new test for writing a new post and checking if an admin notice email was sent.

[code language=”php”]
# test/integration/post_flow_test.rb

require ‘test_helper’

classPostFlowTest> Capybara::Rails::TestCase
includeActiveJob::TestHelper

def setup
@one = posts :one
@two = posts :two
end

test ‘post index’ do
visitposts_path

assertpage.has_content?(@one.title)
assertpage.has_content?(@two.title)
end

test ‘writing a new post’ do
write_new_post

latest_post = Post.last

assert_current_pathpost_path(latest_post)
assertpage.has_content?(‘Test Title’)
assertpage.has_content?(‘Test Body’)
end

test ‘writing a new post’ do
write_new_post

latest_post = Post.last

assert_current_pathpost_path(latest_post)
assertpage.has_content?(‘Test Title’)
assertpage.has_content?(‘Test Body’)
end

test ‘writing a new post sends admin notice’ do
perform_enqueued_jobs do
write_new_post

last_post = Post.last
mail      = ActionMailer::Base.deliveries.last

assert_equal ‘admin@example.com’, mail[‘to’].to_s
assert_equal ‘New post added’, mail.subject
end
end

private

defwrite_new_post
visitposts_path

click_on ‘New Post’

fill_in ‘Title’, with: ‘Test Title’
fill_in ‘Body’,  with: ‘Test Body’

click_on ‘Create Post’
end
end
[/code]

Let’s create the mailer first:

[code language=”php”]
rails generate mailer PostMailer
[/code]

This should set up the mailer – Time to add our admin notice email to it:

[code language=”php”]
# app/mailers/post_mailer.rb

classPostMailer> ApplicationMailer
defadmin_notice(post)
@post = post
mail to: ‘admin@example.com’, subject: ‘New post added’
end
end
[/code]

We also need the corresponding views:

[code language=”php”]
%# app/views/post_mailer/admin_notice.html.erb %>

A new post has been added! Here’s the post:

<%= @post.title %>
<%= simple_format @post.body %>

<%# app/views/post_mailer/admin_notice.text.erb %>

A new post has been added! Here’s the post:

Title: <%= @post.title %>
<%= @post.body %>
[/code]

We’ll skip the tests for this mailer to keep this tutorial from getting too long. All you have to do now is call the mailer from the controller after a post has been created.

[code language=”php”]
# app/controllers/posts_controller.rb


# POST /posts
# POST /posts.json
def create
@post = Post.new(post_params)

respond_to do |format|
if @post.save
PostMailer.admin_notice(@post).deliver_later

format.html { redirect_to @post, notice: ‘Post was successfully created.’ }
format.json{ render :show, status: :created, location: @post }
else
format.html { render :new }
format.json{ renderjson: @post.errors, status: :unprocessable_entity }
end
end
end

[/code]

We added only one line there to call the mailer. Now, let’s run the tests again and see if they pass.

[code language=”php”]
rake

# Running:

……….

Finished in 0.975611s, 10.2500 runs/s, 15.3750 assertions/s.

10 runs, 15 assertions, 0 failures, 0 errors, 0 skips
[/code]

All the tests should pass, and now you have an application that is integration-tested end-to-end with Minitest and Capybara.

Coming To An End of The Lesson

I’ve worked with the team at Andolasoft on multiple websites. They are professional, responsive, & easy to work with. I’ve had great experiences & would recommend their services to anyone.

Ruthie Miller, Sr. Mktg. Specialist

Salesforce, Houston, Texas

LEARN MORE

I am sure this article will give you a clear idea about ruby on rails application integration testing using Minitest and Capybara. Share your thoughts with comments if I have missed anything or if you want to know more.

SQL Injection (SQLi): How To Fix It In Ruby On Rails

What is SQL Injection Vulnerability?

SQL injection is vulnerability where an attacker can manipulate some value used in an unsafe way inside a SQL query. The bug allows SQL injection through dynamic finder methods, leading to data leaks, data loss & other unpleasant outcomes.

Let’s consider the following code to get customer information by email:

[code language=”html”]
Customer.where("email = #{user_data}").first
[/code]

Since the attacker has full control over ‘user_data’, they can insert whatever they like in the ‘where query’. For example:

[code language=”html”]
user_data = “email@somedomain.com; DROP TABLE customers;”
[/code]

The above ‘user_data’ with ‘where query’ will be executed separately as two SQL commands in the database, like this:

[code language=”html”]
SELECT * FORM customers WHERE email=’someone@example.com; DROP TABLE customers;–‘
[/code]

This results in complete data loss from customers table. Apart from data loss, the attackers can get useful information from your database using SQL injection.

Never miss an update from us. Join 10,000+ marketers and leaders.

Here is a sample code where User is being searched by the username:

[code language=”html”]
User.where("username = #{user_data}").first
[/code]

The attacker inserts the following text as ‘user_data’:

[code language=”html”]
user_data = "” or admin=’t’–"
[/code]

The above ‘user_data’ with ‘where query’ works like this:

  • The first part of the ‘user_data’ ‘# returns empty result set as the username is blank.
  • The second part, admin=’t’ fetches admin information from the table.
  • The last part — is a SQL comment to cancel all further command execution.

With this, all information about the admin is now in the attacker’s hands which might lead to serious problems.

Preventing SQL Injection Vulnerability

The best way to find out if an application is vulnerable to injection is to check whether the entire use of interpreters clearly segregates not-to-be trusted data from the command/query. In SQL calls, all the variables should bind with the prepared statements and stored procedures, whereas the dynamic queries should be avoided to prevent SQL vulnerabilities.

ActiveRecord & some other ORMs have all the facilities for parameterising queries. Here are some of the frequently used unsafe queries and safer ways to fix them:

Single Parameter Queries

# Unsafe Query

[code language=”html”]
Post.where("post_title = ‘#{post_title}’")
Post.where("post_title = ‘%{post_title}’" % { post_title: post_title })
[/code]

# Safe Query

[code language=”html”]
Post.where(post_title: post_title)
Post.where("post_title = ?", post_title)
Post.where("post_title = :post_title", post_title: post_title)
[/code]

Compounding Queries

# Unsafe Query

[code language=”html”]
def unsafe_query
query = []
query << "post_title = #{post_title}" if condition1
query << "author = #{author}" if condition2
Post.where(query.join(‘ and ‘))
end
[/code]

# Safe Query

[code language=”html”]
def safe_query
Post.all.tap do |query|
query.where(post_title: post_title) if condition1
query.where(author: author) if condition2
end
end
[/code]

Like Query

# Unsafe Query

[code language=”html”]
Post.where("post_title LIKE ‘%#{post_title}%’")
[/code]

# Safe Query

[code language=”html”]
Post.where("post_title LIKE ?", "%#{post_title}%")
[/code]

Conclusion

From the above mentioned Unsafe vs Safe illustrations, it’s clear that if there is a surrounding quote to the query, it’s vulnerable to SQL Injection. Thanks to clever methods, this is hardly a problem in most Rails applications now-a-days. However, this is a very common but devastating attack in the world of web apps.

Hence, it’s important to understand the problem & fix it as described above.

If you’re worried about the security of your Ruby on Rails App, we would be happy to help you. If you’re planning to start something new on RoR, get in touch with us. We’ll convert your ideas into app.

Module In Ruby And Its Usages In Rails

Ruby is an Object Oriented Programming (OOP) language. This programming language based upon various components such as classes, object, variables etc. Ruby also provides a nice building block for applications, and which is known as module. A module is a collection of methods and constants. It defines a namespace in which other methods and constant can’t step on your methods and constants.

Purpose of a Module:

Ruby module is a component to regroup similar things. Ruby methods, classes and constants can be grouped by similarity with the help of modules.

Here is the Two benefits provide by the modules

  • Ruby provide ‘namespace’, and which basically helps to prevent name clashes.
  • Ruby’s ‘mixin’ facility is implemented with the help of modules.

The basic syntax of module is:

[code language=”html”]
module Identifier
statement1
statement2
………..
End
[/code]

Uses:

Ruby module mainly functions as a namespace. It lets us define various methods for the actions that will perform. When a method defined inside a module does not clash with other methods that are written anywhere else, though they’re having the same names.

Module constants are named like class constants with an initial uppercase letter. This are module methods, and also defined like class methods.

Here is an example.

[code language=”html”]
module MyModule
def method
puts “hello”
end
end
[/code]

To access the methods and constants inside a module in a class include key word is used.

[code language=”html”]
class Customer < ActiveRecord::Base
include MyModule
end
[/code]

To use the method that is defined inside a module, specify the module name followed by a dot and then the method name.

Ruby Mixins and Ruby Modules:

Ruby is purely an OOP language. But it does not support multiple inheritances directly, which is handled beautifully by Modules. They provide a facility called ‘mixin’ that eliminates the requirement of multiple inheritance. In Ruby when ‘mixins’ are called and used in proper manner they provide high degree of versatility functionality.

Never miss an update from us. Join 10,000+ marketers and leaders.

A module ‘mixin’ generally consists of several lines of codes to set up conditions where the module can mix in with a class or classes to improve the functionality of the class or itself too. Here is an example of a module ‘mixin’.

[code language=”html”]
module A
def a1
end
def a2
end
end

module B
def b1
end
def b2
end
end

class MyClass
include A
include B
def s1
end
end

obj = Objet.new
obj.a1
obj.a2
obj.b1
obj.b2
obj.s1
[/code]

Here module A and B consist of two methods individually. They are included in the classMyClass. Now MyClass can access all the four methods a1, a2, b1, b2. So it can be said that Myclass inherits from multiple modules. Thus multiple inheritances are implemented with the help of module’s ‘mixin’ facility.

Conclusion:

Modules don’t have any direct analogy in any mainstream programming language. They are used mostly in Ruby language. They are one of the key features making Ruby’s design beautiful. With the facility of ‘namespacing’ and ‘mixin’ modules make Ruby more flexible Object Oriented Programming language. They also make the application highly secure as classes and their objects inherit from modules and modules are having ‘mixins’.

Planning something with RoR? We would love to get in touch with you.

Why Ruby is Getting Popular Among Languages?

Ruby is an object-oriented programming language, and it tries to keep things simple to boost productivity. Yukihiro Matsumoto from Japan has design this Framework in the year 1995. With time, Ruby has gained a wide reputation in the Internet World and adopted by many programmers. It is also known as a developer’s best friend. With Ruby on Rails Framework, more efficient and fast web applications are developed and the numbers are increasing. The latest stable release is version 2.2.2.

The developer considers the advantages and extra features of this language when choosing this programming language. As being Opensource, developer can modify the codes and share it with others. The Framework has a rich library support which is very helpful in optimizing the code.

Never miss an update from us. Join 10,000+ marketers and leaders.

Ruby is a High Level Programming language and it uses a strong abstraction of a computer. Its syntax is more like a natural language which is very easy to understand.

It’s Your Turn To Make Things Better With Ruby

Ruby on Rails is now hot in the market as it does provide the most productive way to build Web based apps. Minimizes the code, adding effective time management as it’s the most crucial perspective in today’s market.

At Andolasoft, we help you to build custom software that can help your business differentiate itself from others and provide a deep competitive advantage through data collection, visualization, and distribution at the edges of your organization. Ruby on Rails makes these type of software development economical.

The facts we have shown above would have made you aware and upgrade your knowledge about The Language. We are sure this article will be of help.

We welcome your comments. Please Visit Andolasoft’s Ruby on Rails Service for more information and details. You can also write to us at info@andolasoft.com. Send us your inputs in under the comments section below and don’t forget to share with your family ‘n’ friends!

Rails Or Django – Which One To Choose?

Rails or Django - which one to choose?

Python and Ruby are the most popular dynamic programming languages. Developers are using these two languages for high-level application development. Python and Ruby are popular among web developers because of their rapid development cycle.

Here, I have discussed the most important difference between Python and Ruby:

Philosophy

Python has been designed to emphasize the programmer’s productivity and code readability. The philosophy of Python requires almost everything explicitly defined by a programmer, whereas Ruby allows programmers to reuse the in-built components in development.

The philosophy behind Ruby is that programmers should have the flexibility and privilege to write concise and compact code.

Functional Programming

Both Rails and Django use object-relational mapping to link the application to the underlying database. In Django, the developer is required to explicitly specify each attribute of every class.

But, In rails, all module attributes are not defined in the class definition. A developer can retrieve all the information from the database based on the class name.

In Rails database migrations is very easy and in-built compared to Django, as it uses third party library like South.

Convention over Configuration

Ruby on Rails defines certain features that make web programming more effective and user-friendly. Convention over configuration (CoC) is one of the important features of Rails.

“Convention over Configuration” means a developer only needs to specify unconventional aspects of the application. There are some predefined layout and sensible defaults available in rails projects.

All components such as models, controllers, and static CSS and JavaScript files are located in standard sub-directories and you just need to drop your implementation files into those directories.

CoC saves a lot of time of developers because in rails you don’t need to write the same code again and again.

While in Django, you have to specify the path where the component files are located. So the development cycles in Rails are shorter as compared to it’s counterparts.

Model-View-Controller and REST

Ruby on Rails is unique because it supports the REST protocol. It helps you to organize your application. In Rails, all model objects are accessed and handled in a uniform manner using the standard HTTP verbs like getting, PUT, DELETE, and POST.

CSS, JavaScript and images

Rails have an in-built asset pipeline. Rails’ asset pipeline is having feature of minifying, concatenating and compressing JavaScript and CSS files. Not only that, it also supports other languages such as Coffeescript, Sass and ERB.

Django’s support of assets it very amateurish compared to Rails and leaves everything to the developer. Django offers static files, which basically collects all static files from each application to a single location.

URL mapping

Both Rails and Django allow for the use of regular expressions to customize the mapping of URLs to controller actions. Both are flexible enough to allow you to create pretty much any mapping scheme you wish.
But, Rails does automatic URL mapping based on the class and function names within controllers by default.

Testing

Testing is very easy in Rails and there’s a much stronger emphasis on it in Rails than in Django.

Popularity

Python is generally more widely used than Ruby. Due to the rising popularity of the Ruby on Rails Web application development framework, Ruby’s popularity to has seen rapid growth.

Both Rails and Django are effective web frameworks powered by efficient programming languages. However, Rails is the best platform for rapid web app development.

Andolasoft offers quality rails development service. We specialize in developing database-driven web applications in an efficient and hassle-free way.

Recommended Blog: Steps to add ‘Elasticsearch’ to Rails App

Have something to add to this topic? Share it in the comments

5 Reasons Why Web Development is Faster With Ruby On Rails

Ruby on Rails aka “RoR” is an open-source MVC framework built using the Ruby programming language.

It is considered as the epitome of the latest generation of high-productivity, open source web development tool. The growing demand for Ruby on Rails has been driven by successful RoR development companies like Andolasoft, who benefit from the speed and agility of building applications in Rails, which results in increased productivity and company growth.

1. Framework Built on Agile Methodology

RoR is faster because the framework was built based on Agile development methodology, best practices are emulated so web development is done with high quality and speed.

RoR framework includes support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together the different components to enable development of a project or solution.

Never miss an update from us. Join 10,000+ marketers and leaders.

It’s possible to build sites that used to take 12 weeks in just 6 weeks using Ruby on Rails. It means you can save 50% on your development expenses.

2. Less Code Writing

Rails creates a skeleton for an application or module by executing all the code libraries. You must write some commands to accomplish this. This is what makes the process of web development faster.

Rails makes database deployments simpler than any open, or proprietary solution by allowing for migrations.

  • Adopting principle of DRY

    It also adopts the principle of “Don’t Repeat Yourself”. So all information can be retrieved from a single unambiguous database which tends to easier development.

  • Easy Configuration

    A key principle of Ruby on Rails development is convention over configuration. This means that the programmer does not have to spend a lot of time configuring files in order to get setup, Rails comes with a set of conventions which help speeding up development.

  • Modular Design

    Ruby code is very readable and mostly self-documenting. This increases productivity, as there is little need to write out separate documentation, making it easier for other developers to pick up existing projects.

  • Designer Friendly Templates

    HTML templates is a core feature of Rails. It allow templates to be composed of a base template that defines the overall layout of the page,the base template is called a “layout” while the individual page templates are “views”. The Rails application retrieves the list of tags from the database and makes it available to the view.The section of the view that renders these category is:

    <%= render :partial => 'category' %>

    This refers to a Ruby partial, a fragment of a page, which is contained in _category.html.erb. That file’s content is:

<h3>categories</h3>
<p class="categorylist">
<%= render :partial => 'categorylist', :collection => @category %>
</p>
  • This generates the heading then refers to another partial, which will be used once for each object in the collection named “categorylist”.

3. Third Party Plugin/Gem Support

Mature plugin architecture, well used by the growing community. Rails plugins allows developer to extend or override nearly any part of the Rails framework, and share these modifications with others in an encapsulated and reusable manner.

Rails community provides a wealth of plugins as Ruby Gems that you simply add to your project Gem-file and install. This significantly accelerates development and maintenance time as you’re not trying to integrate disparate libraries, it’s already done for you.

4. Automated Testing

Rails has developed a strong focus on testing, and has good testing suit in-built within the frameworks.

Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.

I’ve worked with the team at Andolasoft on multiple websites. They are professional, responsive, & easy to work with. I’ve had great experiences & would recommend their services to anyone.

Ruthie Miller, Sr. Mktg. Specialist

Salesforce, Houston, Texas

LEARN MORE

Rails ships with a built-in test suite. There are many tools available in the market for testing Rails application as mentioned below with other web apps from many different aspects.

  • Rspec
  • Cucumber
  • Test Unit
  • Shoulda
  • Selenium (not really a ruby thing but more of a web thing)

But if you are new to testing we highly recommend you start with learning Rails own testing suite before start using other tools

5. Easier Maintenance

Once site launches, future modifications to your site (e.g., adding new features, making changes to the data model) can be made more quickly, for the same reasons noted above.
New features can be added quickly and maintaining applications over time can also be more cost-effective.

If you like this one, you might also like Why Rails framework popular among Ruby developers and The Best practices for Rails App Development .