SlideShare a Scribd company logo
1 of 8
Download to read offline
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
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.
A lot of you must have heard about Capybara but still for those who are new to this -
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 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 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.
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
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.
# Gemfile
...
group :test do
gem 'minitest-rails-capybara'
end
Also need to load Capybara in order to use it in our tests.
# test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
requireFile.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/rails/capybara"
...
Now, that you have everything set up, let’s see the integration tests with an example
application.
Running the scaffold generator to create posts.
rails generate scaffold Post title:string body:text
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
Next we need to migrate the database.
rakedb:migrate
== 20161214213527 CreatePosts: migrating ======================================
-- create_table(:posts)
-> 0.0020s
== 20161214213527 CreatePosts: migrated (0.0024s) =============================
rake
# Running:
.......
You can also issue rails server at the command line and navigate to
http://localhost:3000/posts to check the result.
Integration Tests
Let's create our first integration test.
# test/fixtures/posts.yml
one:
title: Post Title One
body: Post body one.
two:
title: Post Title Two
body: Post body two.
Here's our first integration test.
# test/integration/post_flow_test.rb
require 'test_helper'
classPostFlowTest< Capybara::Rails::TestCase
def setup
@one = posts :one
@two = posts :two
end
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
test 'post index' do
visitposts_path
assertpage.has_content?(@one.title)
assertpage.has_content?(@two.title)
end
end
All youneed to do here is – to run all your tests again to make sure they all pass
rake
# Running:
........
Finished in 0.515325s, 15.5242 runs/s, 21.3458 assertions/s.
8 runs, 11 assertions, 0 failures, 0 errors, 0 skips
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.
# 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
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
Run the tests again to make sure everything passes.
rake
# Running:
.........
Finished in 0.551475s, 16.3199 runs/s, 23.5731 assertions/s.
9 runs, 13 assertions, 0 failures, 0 errors, 0 skips
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.
# 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
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
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
Let's create the mailer first:
rails generate mailer PostMailer
This should set up the mailer - Time to add our admin notice email to it:
# app/mailers/post_mailer.rb
classPostMailer<ApplicationMailer
defadmin_notice(post)
@post = post
mail to: 'admin@example.com', subject: 'New post added'
end
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
end
We also need the corresponding views:
<%# app/views/post_mailer/admin_notice.html.erb %>
<p>A new post has been added! Here's the post:</p>
<p><%= @post.title %></p>
<%= 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 %>
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.
# 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
...
From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company
We added only one line there to call the mailer. Now, let's run the tests again and see if they
pass.
rake
# Running:
..........
Finished in 0.975611s, 10.2500 runs/s, 15.3750 assertions/s.
10 runs, 15 assertions, 0 failures, 0 errors, 0 skips
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 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.
http://www.andolasoft.com | http://blog.andolasoft.com
Call at 4086257188 or Email at info@andolasoft.com

More Related Content

What's hot

Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
Brandon Keepers
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using Cucumber
KMS Technology
 

What's hot (20)

Behavior Driven Development with Cucumber
Behavior Driven Development with CucumberBehavior Driven Development with Cucumber
Behavior Driven Development with Cucumber
 
Automated Testing in Angular Slides
Automated Testing in Angular SlidesAutomated Testing in Angular Slides
Automated Testing in Angular Slides
 
The road to Ember 2.0
The road to Ember 2.0The road to Ember 2.0
The road to Ember 2.0
 
Karate DSL
Karate DSLKarate DSL
Karate DSL
 
Capybara testing
Capybara testingCapybara testing
Capybara testing
 
Serverless in production, an experience report (London DevOps)
Serverless in production, an experience report (London DevOps)Serverless in production, an experience report (London DevOps)
Serverless in production, an experience report (London DevOps)
 
Rspec
RspecRspec
Rspec
 
Laravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionLaravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello Production
 
BDD in Java using Cucumber
BDD in Java using CucumberBDD in Java using Cucumber
BDD in Java using Cucumber
 
Rails 5 – most effective features for apps upgradation
Rails 5 – most effective features for apps upgradationRails 5 – most effective features for apps upgradation
Rails 5 – most effective features for apps upgradation
 
ASP.NET MVC Extensibility
ASP.NET MVC ExtensibilityASP.NET MVC Extensibility
ASP.NET MVC Extensibility
 
From CakePHP to Laravel
From CakePHP to LaravelFrom CakePHP to Laravel
From CakePHP to Laravel
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using Cucumber
 
Cross-browser testing in the real world
Cross-browser testing in the real worldCross-browser testing in the real world
Cross-browser testing in the real world
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
Laravel 5 New Features
Laravel 5 New FeaturesLaravel 5 New Features
Laravel 5 New Features
 
How to Cover All Your Backend Testing Needs with API and UI Tests
How to Cover All Your Backend Testing Needs with API and UI TestsHow to Cover All Your Backend Testing Needs with API and UI Tests
How to Cover All Your Backend Testing Needs with API and UI Tests
 
Serverless in production, an experience report (linuxing in london)
Serverless in production, an experience report (linuxing in london)Serverless in production, an experience report (linuxing in london)
Serverless in production, an experience report (linuxing in london)
 

Viewers also liked

лютеж 08.05.2012
лютеж 08.05.2012лютеж 08.05.2012
лютеж 08.05.2012
AZBI
 
Adopt ME!!!!!
Adopt ME!!!!!Adopt ME!!!!!
Adopt ME!!!!!
uavivian
 
Angie Bowden_CV_2016
Angie Bowden_CV_2016Angie Bowden_CV_2016
Angie Bowden_CV_2016
Angie Bowden
 

Viewers also liked (17)

Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702
 
лютеж 08.05.2012
лютеж 08.05.2012лютеж 08.05.2012
лютеж 08.05.2012
 
3. msión
3. msión3. msión
3. msión
 
2. visión
2. visión2. visión
2. visión
 
mi casa
mi casa mi casa
mi casa
 
Da putri prima
Da putri primaDa putri prima
Da putri prima
 
shaileshfres
shaileshfresshaileshfres
shaileshfres
 
Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702
 
Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702
 
Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702
 
Adopt ME!!!!!
Adopt ME!!!!!Adopt ME!!!!!
Adopt ME!!!!!
 
Angie Bowden_CV_2016
Angie Bowden_CV_2016Angie Bowden_CV_2016
Angie Bowden_CV_2016
 
Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702Pioneer city Bilaspur Gurgaon,9136824702
Pioneer city Bilaspur Gurgaon,9136824702
 
Daniel Roberts resume
Daniel Roberts resumeDaniel Roberts resume
Daniel Roberts resume
 
8. impacto social y ambiental
8. impacto social y ambiental8. impacto social y ambiental
8. impacto social y ambiental
 
Php development and upcoming trends in 2017
Php development and upcoming trends in 2017Php development and upcoming trends in 2017
Php development and upcoming trends in 2017
 
Cap 26 financiamiento y planeacion a corto plazo 9° Ross_Finanzas para la con...
Cap 26 financiamiento y planeacion a corto plazo 9° Ross_Finanzas para la con...Cap 26 financiamiento y planeacion a corto plazo 9° Ross_Finanzas para la con...
Cap 26 financiamiento y planeacion a corto plazo 9° Ross_Finanzas para la con...
 

Similar to Ruby on rails integration testing with minitest and capybara

Query Management system-Iv review
Query Management system-Iv reviewQuery Management system-Iv review
Query Management system-Iv review
logeshprabu
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
Troy Miles
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
Puppet
 

Similar to Ruby on rails integration testing with minitest and capybara (20)

How to implement ruby on rails testing practices to build a successful web ap...
How to implement ruby on rails testing practices to build a successful web ap...How to implement ruby on rails testing practices to build a successful web ap...
How to implement ruby on rails testing practices to build a successful web ap...
 
Capybara and cucumber with DSL using ruby
Capybara and cucumber with DSL using rubyCapybara and cucumber with DSL using ruby
Capybara and cucumber with DSL using ruby
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance Testing
 
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
 
Speedy TDD with Rails
Speedy TDD with RailsSpeedy TDD with Rails
Speedy TDD with Rails
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
TorqueBox
TorqueBoxTorqueBox
TorqueBox
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Deploying Rails Apps with Capistrano
Deploying Rails Apps with CapistranoDeploying Rails Apps with Capistrano
Deploying Rails Apps with Capistrano
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in Rails
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
Query Management system-Iv review
Query Management system-Iv reviewQuery Management system-Iv review
Query Management system-Iv review
 
Beginning AngularJS
Beginning AngularJSBeginning AngularJS
Beginning AngularJS
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Lampstack (1)
Lampstack (1)Lampstack (1)
Lampstack (1)
 
Lessons learned from a huge Rails app - RubyConf Brasil 2019
Lessons learned from a huge Rails app - RubyConf Brasil 2019Lessons learned from a huge Rails app - RubyConf Brasil 2019
Lessons learned from a huge Rails app - RubyConf Brasil 2019
 
Testing Big in JavaScript
Testing Big in JavaScriptTesting Big in JavaScript
Testing Big in JavaScript
 
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Campmodern module development - Ken Barber 2012 Edinburgh Puppet Camp
modern module development - Ken Barber 2012 Edinburgh Puppet Camp
 

More from Andolasoft Inc

More from Andolasoft Inc (20)

Challenges of React Native App Development_ Effective Mitigation Strategies.pdf
Challenges of React Native App Development_ Effective Mitigation Strategies.pdfChallenges of React Native App Development_ Effective Mitigation Strategies.pdf
Challenges of React Native App Development_ Effective Mitigation Strategies.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Essential Functionalities Your Real Estate Web App Must Have.pdf
Essential Functionalities Your Real Estate Web App Must Have.pdfEssential Functionalities Your Real Estate Web App Must Have.pdf
Essential Functionalities Your Real Estate Web App Must Have.pdf
 
A Complete Guide to Developing Healthcare App
A Complete Guide to Developing Healthcare AppA Complete Guide to Developing Healthcare App
A Complete Guide to Developing Healthcare App
 
Game-Changing Power of React Native for Businesses in 2024
Game-Changing Power of React Native for Businesses in 2024Game-Changing Power of React Native for Businesses in 2024
Game-Changing Power of React Native for Businesses in 2024
 
A Complete Guide to Real Estate Website Development
A Complete Guide to Real Estate Website DevelopmentA Complete Guide to Real Estate Website Development
A Complete Guide to Real Estate Website Development
 
How to Build Cross-Platform Mobile Apps Using Python
How to Build Cross-Platform Mobile Apps Using PythonHow to Build Cross-Platform Mobile Apps Using Python
How to Build Cross-Platform Mobile Apps Using Python
 
Impact of AI on Modern Mobile App Development
Impact of AI on Modern Mobile App DevelopmentImpact of AI on Modern Mobile App Development
Impact of AI on Modern Mobile App Development
 
How to Optimize the SEO of Shopify Stores
 How to Optimize the SEO of Shopify Stores How to Optimize the SEO of Shopify Stores
How to Optimize the SEO of Shopify Stores
 
14 Tips On How To Improve Android App Performance
14 Tips On How To Improve Android App Performance14 Tips On How To Improve Android App Performance
14 Tips On How To Improve Android App Performance
 
The Ultimate Guide to Setting Up Your WooCommerce Store
The Ultimate Guide to Setting Up Your WooCommerce StoreThe Ultimate Guide to Setting Up Your WooCommerce Store
The Ultimate Guide to Setting Up Your WooCommerce Store
 
Ranking The Best PHP Development Companies in the World
Ranking The Best PHP Development Companies in the WorldRanking The Best PHP Development Companies in the World
Ranking The Best PHP Development Companies in the World
 
Top 8 WordPress Design and Development Trends of 2023
Top 8 WordPress Design and Development Trends of 2023Top 8 WordPress Design and Development Trends of 2023
Top 8 WordPress Design and Development Trends of 2023
 
List of 10 Best WordPress Development Companies
List of 10 Best WordPress Development CompaniesList of 10 Best WordPress Development Companies
List of 10 Best WordPress Development Companies
 
WooCommerce vs Shopify: Which is Better For Your Online Store
WooCommerce vs Shopify: Which is Better For Your Online StoreWooCommerce vs Shopify: Which is Better For Your Online Store
WooCommerce vs Shopify: Which is Better For Your Online Store
 
Why Choose WooCommerce For Your eCommerce Store
Why Choose WooCommerce For Your eCommerce StoreWhy Choose WooCommerce For Your eCommerce Store
Why Choose WooCommerce For Your eCommerce Store
 
Django Workflow and Architecture
Django Workflow and ArchitectureDjango Workflow and Architecture
Django Workflow and Architecture
 
Service Oriented Architecture in NodeJS
Service Oriented Architecture in NodeJSService Oriented Architecture in NodeJS
Service Oriented Architecture in NodeJS
 
Top Features And Updates Of Angular 13 You Must Know
Top Features And Updates Of Angular 13 You Must KnowTop Features And Updates Of Angular 13 You Must Know
Top Features And Updates Of Angular 13 You Must Know
 
How To Organize And Structure Your SASS Code
How To Organize And Structure Your SASS CodeHow To Organize And Structure Your SASS Code
How To Organize And Structure Your SASS Code
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
Wonjun Hwang
 
Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
Overkill Security
 

Recently uploaded (20)

State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)CORS (Kitworks Team Study 양다윗 발표자료 240510)
CORS (Kitworks Team Study 양다윗 발표자료 240510)
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Microsoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdfMicrosoft BitLocker Bypass Attack Method.pdf
Microsoft BitLocker Bypass Attack Method.pdf
 

Ruby on rails integration testing with minitest and capybara

  • 1. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company 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. A lot of you must have heard about Capybara but still for those who are new to this - 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 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 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.
  • 2. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company 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. # Gemfile ... group :test do gem 'minitest-rails-capybara' end Also need to load Capybara in order to use it in our tests. # test/test_helper.rb ENV['RAILS_ENV'] ||= 'test' requireFile.expand_path('../../config/environment', __FILE__) require 'rails/test_help' require "minitest/rails/capybara" ... Now, that you have everything set up, let’s see the integration tests with an example application. Running the scaffold generator to create posts. rails generate scaffold Post title:string body:text
  • 3. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company Next we need to migrate the database. rakedb:migrate == 20161214213527 CreatePosts: migrating ====================================== -- create_table(:posts) -> 0.0020s == 20161214213527 CreatePosts: migrated (0.0024s) ============================= rake # Running: ....... You can also issue rails server at the command line and navigate to http://localhost:3000/posts to check the result. Integration Tests Let's create our first integration test. # test/fixtures/posts.yml one: title: Post Title One body: Post body one. two: title: Post Title Two body: Post body two. Here's our first integration test. # test/integration/post_flow_test.rb require 'test_helper' classPostFlowTest< Capybara::Rails::TestCase def setup @one = posts :one @two = posts :two end
  • 4. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company test 'post index' do visitposts_path assertpage.has_content?(@one.title) assertpage.has_content?(@two.title) end end All youneed to do here is – to run all your tests again to make sure they all pass rake # Running: ........ Finished in 0.515325s, 15.5242 runs/s, 21.3458 assertions/s. 8 runs, 11 assertions, 0 failures, 0 errors, 0 skips 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. # 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
  • 5. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company Run the tests again to make sure everything passes. rake # Running: ......... Finished in 0.551475s, 16.3199 runs/s, 23.5731 assertions/s. 9 runs, 13 assertions, 0 failures, 0 errors, 0 skips 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. # 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
  • 6. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company 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 Let's create the mailer first: rails generate mailer PostMailer This should set up the mailer - Time to add our admin notice email to it: # app/mailers/post_mailer.rb classPostMailer<ApplicationMailer defadmin_notice(post) @post = post mail to: 'admin@example.com', subject: 'New post added' end
  • 7. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company end We also need the corresponding views: <%# app/views/post_mailer/admin_notice.html.erb %> <p>A new post has been added! Here's the post:</p> <p><%= @post.title %></p> <%= 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 %> 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. # 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 ...
  • 8. From the Resource Library of Andolasoft.Inc | Web and Mobile App Development Company We added only one line there to call the mailer. Now, let's run the tests again and see if they pass. rake # Running: .......... Finished in 0.975611s, 10.2500 runs/s, 15.3750 assertions/s. 10 runs, 15 assertions, 0 failures, 0 errors, 0 skips 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 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. http://www.andolasoft.com | http://blog.andolasoft.com Call at 4086257188 or Email at info@andolasoft.com