Welcome!

Ruby-On-Rails Authors: Liz McMillan, Pat Romanski, Elizabeth White, Hovhannes Avoyan, Yeshim Deniz

Related Topics: Java IoT, Microservices Expo, Open Source Cloud, Machine Learning , Agile Computing, Ruby-On-Rails

Java IoT: Blog Post

Faster Test Suite Boot Times with Ruby on Rails

Learn how to reduce startup times for your Ruby on Rails test suite. We talk about dependencies, stubs and factories.

Let's jump into an example. We're assuming you're using the following, simplified, Gemfile for your dependencies:

gem "rails"
gem "bcrypt"
gem "foreman"
gem "thin"
gem "newrelic_rpm"
gem "airbrake"

First we stop loading gems which aren't used in the code.

gem "rails"
gem "bcrypt"
gem "foreman", require: false
gem "thin", require: false
gem "newrelic_rpm"
gem "airbrake"

Then we make sure dependencies are only specified for the environments where they're used in.

gem "rails"
gem "bcrypt"

group :development do
  gem "foreman", require: false
end

group :production do
  gem "thin", require: false
  gem "newrelic_rpm"
  gem "airbrake"
end

At this point you might start getting undefined constant errors about Airbrake. You can decide to either move Airbrake back into all environments or stub its implementation.

We generally do this by defining the module or class ourselves from a support file in the test directory, like so:

module Airbrake
    extend self
    def notify(exception, opts = {})
    end
  end

Partial example of a stub implementation for Airbrake.

On the one hand you probably never want to send data from your test suite to Airbrake. On the other hand some people are more comfortable running their entire production stack in at least one or two tests.

Reduce time spent setting up tests
Basically you need to do less. There are a few strategies to accomplish this.

One strategy is moving setup code as local to your test as possible so it only runs for the tests where it's needed. For example, don't run setup methods specific for functional tests in unit test.

Keep in mind that your test_helper.rb or spec_helper.rb is loaded during every boot. Try to limit slow operations in this file.

Tests that require long setup tasks sometimes need to be run in a variety of contexts: library tests, model tests, and functional tests. Sometimes you can cheat a little bit and test through the entire stack in one massive integration test.

Another strategy is to perform long setup tasks only once and find a way to cache the result to speed up next runs.

In one of our applications we process YAML files with questionnaire definitions and create records for them in the database. In hindsight we should have never done this, but that's a discussion for another day.

In unit and functional tests we use fixtures to test specific situations. For regression tests we need the production definitions. We speed up loading these by dumping the database tables with INTO OUTFILE and load them with LOAD DATA INFILE. We also hook into Rails fixture loading code so it only happens once for the entire suite.

Finally, never, ever, ever, ever, call external services from your tests. Not only is this slow, but it might accidentally erase production data. In most tests we override Net::HTTP#startto make sure it's never called by accident.

Factories or fixtures
There is a lot to say about database setup, so it deserves its own little chapter.

Let's get the elephant out of the room first. Factories are slow! They're slow by design.

Factories can be used to create database records anywhere in your test suite. This makes them pretty flexible and allows you to keep your test data local to your tests. The drawback is that it makes them almost impossible to speed up in any significant way.

We can understand why factories are slow by looking at why ActiveRecord fixtures are fast.

Fixtures are bulk loaded once. A transaction is created in the database when a test starts. After the test the database is rolled back to its initial state. This means the fixtures don't have to be reloaded for each test.

Most factory implementations start a test with an empty database and run through all the factories needed for a test each time it's run. After the test the database is reset to its blank state by removing all records. On top of that records are created through ActiveRecord model instances, which creates a lot of objects in the Ruby VM, which need to be garbage collected.

We try to use fixtures as much as possible. We write little scenarios with them to make tests easier to understand. Paul might be a pro account holder who has paid his bills the last two years, but unfortunately missed a payment this month because his credit card expired.

Using small scenarios like this reduce the chance of someone messing up tests by using the wrong fixture or changing fixtures to not fit their intended scenario. You can even document these scenarios shortly in the fixture files or test helper.

Use a fast test framework

Your test framework needs to be loaded and initialized during every boot.

RSpec is notoriously slow. If you're willing to part with it, you might want to consider minitest/spec. You can use minitest/spec with Rails out of the box since version 4.0. Another alternative is Peck on Rails.

In doubt, measure!

Optimizations don't really make sense when you can't measure the speedups. Most test frameworks print their runtimes, but this doesn't include boot time. The time tool is your friend.

$ time ruby test/unit/post_test.rb
Loaded suite test/unit/post_test
Started
..
Finished in 0.001313 seconds.

2 tests, 6 assertions, 0 failures, 0 errors
ruby test/unit/post_test.rb  0.15s user 0.08s system 96% cpu 0.238 total

In this example test/unit reports 0.001313 seconds, but the real runtime is 0.238.

To measure particular parts of your code you can either use a profiler or the Benchmark class.

Isolate the slow code and keep the benchmark in place to measure if your fix actually helps.

More Stories By Manuel Weiss

I am the cofounder of Codeship – a hosted Continuous Integration and Deployment platform for web applications. On the Codeship blog we love to write about Software Testing, Continuos Integration and Deployment. Also check out our weekly screencast series 'Testing Tuesday'!

@ThingsExpo Stories
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
Most people haven’t heard the word, “gamification,” even though they probably, and perhaps unwittingly, participate in it every day. Gamification is “the process of adding games or game-like elements to something (as a task) so as to encourage participation.” Further, gamification is about bringing game mechanics – rules, constructs, processes, and methods – into the real world in an effort to engage people. In his session at @ThingsExpo, Robert Endo, owner and engagement manager of Intrepid D...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abilit...
In his session at Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to maximize project result...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...