Tag Archives: Ruby on Rails

Selective stubbing of method calls in RSpec

While building a simple API in Rails, I had the following method in my User model that needed to be tested:

def generate_auth_token!
  loop do
    self.auth_token = Devise.friendly_token
    break unless self.class.exists?(auth_token: auth_token)

The method uses Devise’s friendly_token method to generate an authentication token for a new user record. After calling the method once, the loop checks whether a user record with the same auth token already exists. If the answer is positive, the method goes for a second try; otherwise it breaks out of the loop, mission accomplished. Continue reading

Tagged , ,

On Cucumber and testing

This article was originally written as part of an ongoing discussion within the team building the OSRA app.

1. Cucumber.

Any time a component is added to an application, its anticipated benefits must be weighed against the costs of its implementation. Cucumber is a costly framework in terms of development time, developer effort, and cognitive strain on both creators and readers of tests due to the following: Continue reading

Tagged , ,

RSpec 3.0.1 & RubyMine

After the recent RSpec update, warnings started showing up in RubyMine:

Deprecation Warnings: Treating `metadata[:execution_result]` as a hash is deprecated. Use the attributes methods to access the data instead. Called from …/teamcity/rspec3_formatter.rb: line#

(So, RSpec is complaining that RubyMine’s formatter is not accessing its data properly?) The warnings were overwhelming to the point of obscuring the results of running the test. Simple fix: Continue reading

Tagged , ,

Sometimes everyone needs a break

I’ve been working through – and enjoying – the EdX/Berkeley CS169 course for the past couple of months. With a bit of a break between the two halves, I thought I’d start a small Rails project of my own. After including ‘rspec-rails’ in my Gemfile, I ran bundle install and then

$ rails g rspec:install
Could not find generator rspec:install

Continue reading

Tagged , ,

Removing Paperclip attachments

Paperclip’s GitHub page includes the necessary steps to delete an attachment – the model’s attribute that refers to the attachment simply gets set to nil. Here is the full implementation of deleting a user’s profile picture in a Rails app. Start with tests (right?!):


require 'spec_helper'

feature 'Editing Users' do
  let(:user) { FactoryGirl.create(:user) }
  let(:admin) { FactoryGirl.create(:admin) }

  scenario 'removing user profile photo' do
    sign_in_as admin # of course
    visit edit_user_path(user)
    click_link 'Remove profile photo'

    expect(page).to have_content 'User profile photo has been removed.'
    expect(page).not_to have_css("img[src*='user.png']") # file name of the user photo defined in the factory
    expect(page).to have_css("img[src*='paperclip_default.png']") # specified in the User model

Continue reading

Tagged , ,

Paperclip attachments in RSpec factories

Assuming one has a model whose attachments are handled by Paperclip, i.e.

$ rails generate paperclip user photo


class User < ActiveRecord::Base

  has_attached_file :photo

then to generate a test model with FactoryGirl, including the attachment: Continue reading

Tagged , , ,

Testing images with RSpec

To test whether the right image is displayed on a page:

expect(page).to have_css("img[src*='image_name.png']")

i.e. “Expect page to have an <img> tag whose src attribute contains the name of the required image.”

Tagged , ,

Learn to delegate (your model methods)

delegate is neat trick that allows one to write cleaner, neater code. Particularly when dealing with ActiveRecord associations, delegate makes it possible to “outsource” a method to an associated object.

class Book < ActiveRecord::Base

  # has attribute 'author'


class Chapter < ActiveRecord::Base

  belongs_to :book

  delegate :author, to: :book


Continue reading

Tagged , ,

Is it changed?

Rails has some useful methods to check whether an object has changed since first being loaded into memory. Here are some examples:

$ rails console --sandbox

2.1.0 :001 > user = User.find(1)

 => #<User id: 1, name: "Roderick", email: "rod@example.com", created_at: ..., updated_at: ...>

2.1.0 :002 > user.name = 'Jimmy'

 => "Jimmy"

2.1.0 :003 > user.changed?

 => true

2.1.0 :004 > user.changed

 => ["name"]

2.1.0 :005 > user.changes

 => {"name"=>["Roderick", "Jimmy"]}

2.1.0 :006 > user.name_changed?

 => true

2.1.0 :007 > user.email_changed?

 => false

2.1.0 :008 > user.name_was

 => "Roderick"

2.1.0 :009 > user.save

 => true

2.1.0 :010 > user.changed?

 => false

More info here: ActiveModel::Dirty.

Tagged , ,

cycle View Helper

The cycle helper method alternates between the values given to it each time it is called:

$ rails console

2.1.0 :001 > include ActionView::Helpers

2.1.0 :002 > cycle('red', 'white')
 => "red"

2.1.0 :003 > cycle('red', 'white')
 => "white"

Continue reading

Tagged , ,