RSpec Syntax Refenrence

I often use RSpec as my testing library when I code in Ruby. The documentation is not that great so I often use code that I already wrote as syntax reference.

Here I am going to write RSpec::Core and RSpec::Expectations syntax so I can refer it in the future.


Most commonly used:

RSpec.describe 'Common, built-in expectation matchers' do
  example 'Equality' do
    expect('x'+'y').to     eq('xy')   # a == b
    expect('x'+'y').to     eql('xy')  # a.eql?(b)
    expect('x'+'y').not_to be('xy')   # a.equal?(b)

  example 'Strings' do
    expect('abcd').to include('bc')
    expect('abcd').to start_with 'ab'
    expect('abcd').to end_with 'cd'
    expect('abcd').to match /[a-z]+/

  example 'Collections' do
    expect([1, 2, 3]).to include(1, 3)
    expect([1, 2, 3]).to contain_exactly(3, 2, 1) # order not important
    expect({ a: 1, b: 2 }).to include(b: 2)

  example 'Booleans and nil' do
    expect(true).to be true
    expect(false).to be false
    expect('abc').to be_truthy
    expect(nil).to be_falsey
    expect(nil).to be_nil

  example 'Numeric' do
    expect(5).to be > 4
    expect(5).to be >= 4
    expect(5).to be < 6
    expect(5).to be <= 6
    expect(5).to be_between(4, 6).exclusive
    expect(5).to be_between(5, 6).inclusive
    expect(4.99).to be_within(0.02).of(5)

  example 'Errors (exceptions)' do
    expect{ 5 / 0 }.to raise_error(ZeroDivisionError)
    expect{ 5 / 0 }.to raise_error("divided by 0")
    expect{ 5 / 0 }.to raise_error(ZeroDivisionError, "divided by 0")

Predicate matchers
DSL for calling methods that 1.return a boolean value 2. have a name that ends with ?

RSpec.describe 'Predicate matchers' do
  example 'Array' do
    expect([]).to be_empty          # [].empty?

  example 'Hash' do
    expect({a: 1}).to have_key(:a)   # {a: 1}.has_key?(:a)
    expect({a: 1}).to have_value(1)  # {a: 1}.has_value?(1)

  example 'Object' do
    expect(5).not_to be_nil             # 'hi'.nil?
    expect(5).to be_instance_of Fixnum  # 5.instance_of?(Fixnum)
    expect(5).to be_kind_of Numeric     # 5.kind_of?(Numeric)

Predicate matchers work on all objects, including custom classes.

class Widget
  attr_accessor :name, :cost

  def initialize(name, cost)
    @name = name
    @cost = cost

  def has_cliche_name?
    ['Foo', 'Bar', 'Baz'].include?(@name)

  def hacker?
    @cost == 1337

RSpec.describe 'Predicate matchers' do
  example 'With a custom class' do
    widget ='Foo', 1337)

    expect(widget).to have_cliche_name
    expect(widget).to be_hacker
    expect(widget).to be_a_hacker
    expect(widget).to be_an_hacker

Advanced matchers

# Add one extra method to the Widget class above,
# for demonstrating change observation.
class Widget
  def fifty_percent_off!
    @cost /= 2

RSpec.describe 'Advanced matchers' do
  example 'Change observation' do
    widget ='Baz', 80)

    expect{ widget.has_cliche_name? }.not_to change(widget, :name)

    expect{ widget.fifty_percent_off! }.to change(widget, :cost) # 80 -> 40
    expect{ widget.fifty_percent_off! }.to change(widget, :cost).from(40).to(20)
    expect{ widget.fifty_percent_off! }.to change(widget, :cost).by(-10) # 20 -> 10

  example 'Object attributes' do
    # The attributes are a hash of method names to
    # expected return values.
    expect('hi').to have_attributes(length: 2, upcase: 'HI')

  example 'Yielding to blocks' do
    expect{ |b| 5.tap(&b) }.to yield_control
    expect{ |b| 5.tap(&b) }.to yield_with_args(5)
    expect{ |b| 5.tap(&b) }.to yield_with_args(Integer)
    expect{ |b| 5.tap(&b) }.not_to yield_with_no_args
    expect{ |b| 3.times(&b) }.to yield_successive_args(0, 1, 2)

  example 'Output capture' do
    expect{ puts 'hi' }.to output("hi\n").to_stdout
    expect{ $stderr.puts 'hi' }.to output("hi\n").to_stderr

  example 'Throws' do
    # Not to be confused with errors (exceptions).
    # Throw/catch is very rarely used.
    expect{ throw :foo, 5 }.to throw_symbol
    expect{ throw :foo, 5 }.to throw_symbol(:foo)
    expect{ throw :foo, 5 }.to throw_symbol(:foo, 5)

  example 'All elements in a collection' do
    expect([3,5,7]).to all(be_odd)
    expect([3,5,7]).to all(be > 0)

  example 'Compound matchers' do
    expect(5).to be_odd.and be > 0
    expect(5).to be_odd.or be_even

    # These are probably most useful in combination with
    # the `all` matcher (above). For example:
    expect([1,2,3]).to all(be_kind_of(Integer).and be > 0)

  example 'Satisfy' do
    # Test against a custom predicate
    expect(9).to satisfy('be a multiple of 3'){ |x| x % 3 == 0 }


Most Commonly used

RSpec.describe 'an array of European cities' do
  let(:cities_array) { [:Berlin, :Prague, :Warsaw] }

  it 'has three cities' do
    expect(cities_array.size).to eq(3)

  context 'mutation' do
    after { expect(cities_array.size).not_to eq(3) }

    it 'can have cities added' do
      cities_array << :Budapest
      expect(cities_array).to eq([:Berlin, :Prague, :Warsaw, :Budapest])

    it 'can have cities removed' do
      expect(cities_array).to eq([:Berlin, :Prague])


The subject key word accesses the object under test. Recreated for every test.

RSpec.describe Array do
  it 'provides methods based on the `RSpec.describe` argument' do
    # described_class = Array
    expect(described_class).to be(Array)
    # subject =
    expect(subject).to eq(
    # is_expected = expect(subject) eq(

  context 'explicitly defined subject' do
    # subject can be manually defined
    subject { [1,2,3] }
    it 'is not empty' do
      is_expected.not_to be_empty

  context 'can be named' do
    # you can provide a name, just like `let`
    subject(:bananas) { [4,5,6] }
    it 'can be called by name' do
     expect(bananas.first).to eq(4)


Run arbitrary code before and after each test or context.

RSpec.describe 'Hooks' do
  order = []

  before(:all) { order << 'before(:all)' }
  before       { order << 'before' }
  after        { order << 'after' }
  after(:all)  { order << 'after(:all)'; puts order }

  around do |test|
    order << 'around, pre'
    order << 'around, post'

  it 'runs first test' do
    order << 'first test'

  it 'runs second test' do
    order << 'second test'

Execution order for the tests above:

around, pre
first test
around, post
around, pre
second test
around, post


Momentarily prevents tests from being run.

RSpec.describe 'Ways to skip tests' do
  it 'is skipped because it has no body'

  skip 'uses `skip` instead of `it`' do

  xit 'uses `xit` instead of `it`' do

  it 'has `skip` in the body' do

  xcontext 'uses `xcontext` to skip a group of tests' do
    it 'wont run' do; end
    it 'wont run either' do; end


Temporarily ignore failing tests.

RSpec.describe 'Ways to mark failing tests as "pending"' do
  pending 'has a failing expectation' do
    expect(1).to eq(2)

  it 'has `pending` in the body' do
    pending('reason goes here')
    expect(1).to eq(2)

  pending 'tells you if a pending test has been fixed' do
    # Pending tests are supposed to fail. This test passes,
    # so RSpec will give an error saying that this pending
    # test has been fixed.
    expect(2).to eq(2)

Helper Methods
Define arbitrary methods for use within your tests.

RSpec.describe 'Defining methods' do
  def my_helper_method(name)
    "Hello #{name}, you just got helped!"

  it 'uses my_helper_method' do
    message = my_helper_method('Susan')
    expect(message).to eq('Hello Susan, you just got helped!')

  context 'within a context group' do
    it 'can still use my_helper_method' do
      message = my_helper_method('Tom')
      expect(message).to eq('Hello Tom, you just got helped!')

Shared examples

A reusable set of tests that can be included into other tests.

RSpec.shared_examples 'acts like non-nil array' do
  it 'has a size' do
    expect(subject.size).to be > 0

  it 'has has non-nil values for each index' do
    subject.size.times do |index|
      expect(subject[index]).not_to be_nil

RSpec.describe 'A real array' do
  include_examples 'acts like non-nil array' do
    subject { ['zero', 'one', 'two'] }

RSpec.describe 'A hash with integer keys' do
  include_examples 'acts like non-nil array' do
    subject { Hash[0 => 'zero', 1 => 'one', 2 => 'two'] }

Shared context;

A reusable context setup (hooks, methods and lets) that can be included into other tests.

RSpec.shared_context 'test timing' do 
 around do |test|
  start_time =
  end_time =
  puts "Test ran in #{end_time - start_time} seconds

RSpec.describe 'big array do 
  include_context 'test timing'
   it 'has many elements' do
     big_array = (1..1_000_000).to_a
     expect (big_array.size).to eq(1_000_000)

Two Months After: Thoughts On Working Remotely

I love working remotely! I was never fit to work in the cubicle. I did so after I graduated from college for a total of three years and I was scarred for life. It is not that I am averse to offices. I simply now appreciate choices and I am inclined to go to one, but not everyday and no more than three times a week.

The transition to working from an office to a home, cafés or friends’ places happened gradually. I freelanced on short term projects where I set my own work time. The feeling was nothing short of liberating and by the end of 2015, I set as my professional goal to work remotely full-time and long-term on a project/company that is meaningful to me. I managed to find it and today I work with the amazing individuals at In this blog post, I would like to share my thoughts and some lessons I took while working full-time during the past two months.

The advantages of working remotely is evident. I don’t face a daily commute, I have the possibility to set my own schedule, work wearing only underwear(or none at all) and code from wherever I am able to produce my best material. In the right distributed team, it is liberating and I feel like an adult for being trusted and feel responsibility for the success of the team/company. The disadvantages though are less documented. I may feel lost, judge myself to the point of creating technical neurosis for not delivering as fast I want or as consistent as my peers, and fall short on maintaining a healthy life-style. In order to mitigate the effects of the downside of working from afar, three habits work for me: keeping a healthy schedule, communicating trust, and being aware of my concentration flow.

Maintaining a Healthy Schedule
One of the challenges I struggle still while working remotely is maintaining a healthy schedule. The time difference between my co-worker and I is 9 hours. I enjoy working with him on technical problems and I end up learning a ton. There have been many days that I went to bed at 4am like this. However, I have noticed that on the days I pull all-nighters I feel exhausted later and more susceptible to be unfocused. We are now attempting to overlap only a few hours per day to get the best of both worlds: keep our rapport and at same time maintain a healthy schedule. I feel the benefits already. The message here is to be aware of your body and productivity swings during the schedule you set for yourself. Am I fresh and ready to focus during the time allotted? Do I have time for myself and to exercise during that time? My next step is to experiment setting a fixed schedule for myself. Do I work best 8 hours straight from x to y or 4 hours in the morning and 4 at night?  The assumption is that by setting a routine, my body and mind will look forward to it and will be prepared for some action when it is time.

Communicating Trust
My observation is that remote teams are bound by trust. There are no walls or someone watching over you shoulder, micromanaging or babysitting you. It is basically a group of individuals that trust each other with one common objective.  This trust comes from creating an environment that communication is encouraged and it is judgement-free. I witness in the team that I work a tremendous amount of trust. Each person is self-managed and live by what they say that are doing that day. This makes me a valued and engaged human-being and consequently leads me to ask myself at each working day
"How can I best support and contribute today given goal X?"

I make sure to express my work intentions and communicate any obstacles I have towards achieving it to the group. Building trust is checking with myself if I am doing the things I said I would do.

Finding The Concentration Flow
Whoever worked on solving a technical problem knows about or experienced themselves winding up in a rabbit hole where 8 hours of dedicated work can result in 5 characters worth of output. I have had in the past two months peaks of output followed by lows where I was blocked by an issue or tried to get my head around one concept. During the low times, I would judge myself and feel pressured to perform. This would lead to stress and not having fun. As a matter of fact I was dedicating long periods of time working at a problem at a time. The solution I found here was to time-box myself to each planned activity. Now I work in 25 minute sessions (a.k.a. Pomodoro technique) and I log goals for each one of these sessions and in the end the actual output I was able to produce.

Here is an example:

G=goal A=actual
G: Wistia video implementation
A: Partially implemented. Getting errors when string interpolating a ng-class

G: Solved the error related to string interpolation
A: Did it. Started creating wistiaDirective


By doing this, I become more aware of my progress, get a consistent concentration flow and realize sooner if I need any help in solving a problem.

To put my thoughts into writing makes me appreciative for the past two months. It makes me more aware of what works for me in this remote work setting and I am able to reflect the challenges I had as well as the lessons I learned from them. Love it! May I have many more of these months to come!

Javascript Module Pattern defines ‘module’ as a self contained unit or item. In programming I like to think of modules as independent pieces of code that can be used to construct a more complex structure. The module pattern in JavaScript is essentially a way to modulize JS code in an application.

This is an example of the module pattern:

var Module = function() {
  var privateProperty = 'foo';

  function privateMethod() {
    // do something

  return {
    publicProperty: "",
    publicMethod: function(args) {
      // do something
    privilegedMethod: function(args){

The code above is an overview of the module pattern. Its aim is Continue reading “Javascript Module Pattern”

The meaning of ‘this’

In JavaScript, just like in real life, context is everything. 
And, just like in other programming languages,
 JavaScript has a special keyword to give access to a specific context.

The this keyword can be used to access values, methods,
and other objects on a context specific basis.
Meaning, this changes based on where it is used.
That is what makes this so powerful and
 it’s also what makes it such a huge headache to understand.

Let’s check out how the this keyword can be
used to do some pretty dynamic and cool things.

Continue reading “The meaning of ‘this’”

Javascript Closure

A closure in Javascript happens when you return a function from inside a function. And This inner function retains access to the scope of the outer function.

var closureAlert = function() {
 var x = 0;
 var alerter = function(){
 return alerter;

 var callClosure = closureAlert();

 var callClosure(); // 1
var callClosure(); // 2 and so on and so forth

callClosure is an example of a closure. It is defined Continue reading “Javascript Closure”

Web Scraping Ajax Heavy Page with Ruby

In the comment section of my previous blog post an WordPress user named Dr Slater asked if I could help out solving a coding problem. This is Dr Slater’s request:

I need a crawl to count the frequency of each users name on this page, and then hash it as an array or a similar solve, where the most frequently occurring user name is max (ranked 1) and least occurring user name is min

I believe one learns better when trying to solve problems oneself (questions are always welcomed of course). But at the same time I can see how this task can be daunting for a new person to coding. So Dr Slater I am going to do the best of both worlds. Here I will lay out how I would do this so you are able to accomplish it yourself.

Programming Language

You are able to crawl a web page with any programming language of your choice. Here I will be using ruby, a language that I find it a joy to use and is user friendly. More info about installing ruby can be found here.

Ruby Library

I will be using watir-webdriver, nokogiri and open-uri which are ruby libraries that will help us with this job. I noticed that the website has awfully layout data with multiple ajax requests that are not friendly to web scraping. I guess that is the price to pay when using different third party plugins for a WordPress site. I must admit I had to summon some of the Jedi powers to do this.

Anyways, after installing ruby, go to the command line interface of your computer(if you are using OSX or Linux operating system it will be “terminal”) and type

 gem install watir-webdriver
 gem install nokogiri

The Code

After this set up, let’s get to it.

Create a file for your script

 touch vindex_rank_scraping.rb

Open this file in your favorite coding editor. I personally use Atom and recommend it.

And add this script to the code editor(Caveat: not the prettiest code but served the purpose for a quick job)

#load the libraries 
require 'nokogiri'
require 'open-uri'
require 'watir-webdriver'

#instance of watir webdriver where we open the page with firefox
browser = :firefox
#self explanatory
browser.goto ""
# giving some time for website to load
sleep 2

# start a nokogiri instance where we store the page's html
data = Nokogiri::HTML(browser.html)

#we will use this to store the links to individual projects so we can go to those pages later
link_to_individual_projects = []

#all the projects are within the div with id category-menu
active_projects = data.css('#category-menu') #

# loop through the categories and get their link
active_projects.css('a').each do |link_tag| => link_tag.text)
  sleep 1
  ajax_called_data = Nokogiri::HTML(browser.html)
  card_name = ajax_called_data.css('.bbcard_name') # card where project is
  link_to_project = card_name.css('a').attribute('href').value # href to project
  link_to_individual_projects << link_to_project

# let's store here the backers for these projects. We are storing them no matter how much they have donated
backers_array = []

# Go each individual page and collect the backer's name
link_to_individual_projects.each do |page|
 sleep 2 => "Backers")
 backers_tab = Nokogiri::HTML(browser.html)

 funders = backers_tab.css('#project-funders')
 backers_array << funders.text.strip

# Setting up part where we rank the backers
rank =

# iterate over the array, counting duplicate entries
backers_array.each do |backers_name|
  rank[backers_name] += 1

# show who the good souls are
rank.each do |name, number|
  puts "#{name} appears #{number} times"

Run the Program
Now you can run this script by typing the command

 ruby vindex_rank_scraping.rb

in the command line.

When I did this on Jan 18th 2016 it showed

 No backers yet! appears 2 times

It makes sense as there are no backers yet in the two projects listed on the site.

Dr Slater, good luck with the rest and all the best in your journey.

to_f vs to_d in Ruby

My girlfriend asked me about the difference between to_f (to float) and to_d (to decimal) in Ruby. By the way, the method to_d is a support method from the ruby library “bigdecimal/util”

I figured that the bigdecimal library provides a more precise decimal number than floats. But it was not all.

After some exploration she explained to me that while it is true that to_d is more precise the main difference from to_f is that it does not work with nil.

require 'bigdecimal'
require 'bigdecimal/util'

nil =

nil.to_f #=> 0.0

nil.to_d # => NoMethodError: undefined method `to_d' for nil:NilClass

12.to_d # 12.0

She continues explaining to me that this main reason why she needs to use float not decimal in her code (for example for when a user has not provided a number).

I love learning from her 🙂

New Year Resolution: deep dive in JavaScript

My New Year resolution is to become a master in JavaScript. This blog post will serve more as a reference to me where I can come back to and review things that I have written. Also the act of writing helps me fossilize in my brain these concepts.

I will start by reviewing the concepts I know about Objects, Arrays and Functions.

Update: Jan 20th Adding Nested data, Scope notions as well.

Arrays and objects are ways to organize data in Javascript(JS).


JS allows us to create objects in object literal notation, such as:

var Santa = {};

This Santa is a bit empty so let’s add some properties. Properties are the keys in a key-value data structure.
It looks like this:

 {username: &quot;hack_thon&quot;, age: 23} //where 'username' and 'age' are the properties

Continue reading “New Year Resolution: deep dive in JavaScript”

A Simple But Effective Way to Contribute to Open Source Projects

I use open source code every day. Be it Rails or the myriad of Ruby gems out there, open source is part of my life and work.

To show gratitude to those who volunteered thousand of developing hours to these projects, I often search ways in which I can contribute to them too. Until recently I simply didn’t know how my contribution could be meaningful. But I may have found a simple but effective way to contribute to open source projects.

It all started when I used the MetaInspector gem in one of my projects. After using it, I thought about the amount of time it saved me in developing a url scraping feature I had to do. So I decided to check the gem repo to see if I could add anything to it. I had a look at the issues, looked at the documentation, forked the repo and ran the tests. It was when I noticed that that was some deprecation warnings showing in RSpec. The most recent RSpec is 3.0 so I saw a chance there to update Rspec and to include the new RSpec syntax in the gem tests.

Once I updated the tests, I submitted a pull request and added my comments.
Screen Shot 2015-01-30 at 12.02.13 AM

Jaime Iniesta, the maintainer of the gem, replied to me within minutes.
Screen Shot 2015-01-30 at 12.01.55 AM

I was exhilarated! A simple but relevant contribution was well on its way. I made the modification he suggested and again within minutes I received a feedback.
Screen Shot 2015-01-30 at 10.52.20 PM

My own small but meaningful contribution to an open source project. It made me feel great that day! This experience also made me realize that contribution can be something such as updating tests in gem, adding some CSS to redesign a gem website or write documentation. I hope this post inspires you to contribute something simple but effective in its own way.

It Is Not Who you Influence, It Is How You Influence

Robert White worked at the same company in New York City with me. This was my first job after college and I did sales support. During my three years stint at this corporation, Robert worked there part-time. We immediately took a liking to each other after we met. We shared the trait of not taking the American corporate work environment too seriously.

We would laugh and crack jokes at our more-often-than-not boring and time wasting tasks. We spent a good amount of time talking about culture, world languages and memories from 20th century USA. He was in his 60s and had lived a great life. He was an extraordinary person and my great friend. The kindness and support he gave me during the time I met him was a source of inspiration to me. For this, he’s made a positive impact in my life.

Before I left this company, I asked him if he could write a letter of recommendation so I could apply to a fellowship program in Germany. He did it gladly even during a turbulent period of his life. I didn’t know this then but he had cancer and was about to start chemotherapy for a tumor that had spread to his bones.

It has been a little over a year since Robert passed away and I miss him dearly. As a German language enthusiast as he was, he would be glad to know that the letter of recommendation he wrote ended up helping me getting the research fellowship I so coveted in Germany. Today I am here enjoying the fruits of the kindness and love that he selflessly poured onto a friend.

Robert’s acts and virtues have influenced my life. I am better human being due to this.

Danke schön fur alles Liebster Freund.