Paperclip attachments in RSpec factories

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

$ rails generate paperclip user photo

app/models/user.rb:

class User < ActiveRecord::Base

  has_attached_file :photo
end

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

Advertisements
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'

end

class Chapter < ActiveRecord::Base

  belongs_to :book

  delegate :author, to: :book

end

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 , ,

Defining CanCan Abilities with blocks

This brainteaser came courtesy of Rails 4 in Action and can be found therein as Listing 8.7. The intended purpose of the code is to use the CanCan gem to define user abilities, or more specifically “can”s (such as “can create a project” or “can edit a ticket”) based on permissions given to him by an admin:

app/models/ability.rb:

class Ability
  include CanCan::Ability

  def initialize(user)
    user.permissions.each do |permission|
      can permission.action.to_sym,
          permission.thing_type.constantize do |thing|
            thing.nil? ||
            permission.thing_id.nil? ||
            permission.thing_id == thing.id
      end
    end
  end
end

Continue reading

Tagged ,

do..end vs {}: Not just a matter of style!

“Use curly braces for single-line blocks and do..end for multi-lines blocks.” Having seen various permutations of that statement dozens of times, I came to believe that the difference between the two was purely stylistic and that there was no practical reason to opt for one vs. the other. Most of the time, that is, indeed, true. Until that one-time-in-a-thousand when it’s not. Continue reading

Tagged , , , ,

.try

This Ruby method returns nil rather than raising an exception when called on a non-existent object.

$ rails console

2.1.0 :001 > nil.admin?
NoMethodError: undefined method 'admin?' for nil:NilClass
... stack trace ...

2.1.0 :002 > nil.try(:admin)
 => nil

Continue reading

Tagged ,

Avoid RSpec and Capybara naming conflicts

There I was, testing user authorization within the Posts controller of my blogging app, when I hit a wall:

describe 'authorization' do
  .
  .
  describe 'in the Posts controller' do
    .
    .
    describe 'attempting to issue a direct POST request without being signed in' do
      before { post posts_path }
      specify { expect(response).to redirect_to signin_path }
    end
  end
end

Simple. But it fails. It works just fine a few dozen lines above within the “Users controller” test block, but fails here. What gives?

Continue reading

Tagged , ,

Just a little proud of my Ruby


Topic 1:

<%= link_to pluralize(topic.posts.count, 'article'), topic_path(topic) %>

on this topic written by

<%= sanitize(topic.posts.map { |p| link_to(p.user.name, user_path(p.user)) }.uniq.join ', ') %>