c a n d l a n d . n e t

Some Rails Tips and Tricks

Dusty Candland | | delayed job, factorygirl, rails, rspec, ruby, testing

After doing a lot of refactoring today I wanted to note a few useful things I’ve picked up.

load the rails environment for rake

If you need to run a rake task that need access to the Rails models, etc. add the :environment dependency

task :my_task => :environment do
end

Testing Delayed Job

Added the following to tell Delayed Job to run without delays.

Delayed::Worker.delay_jobs = false

Or the following to run a last Job and check for Success and Fail, in the returned array.

Delayed::Worker.new.work_off.should == [1, 0]

Check the Job Count with one of the following

Delayed::Job.count.should == 1

# OR

lambda do
# code the should schedule a delayed job
end.to change(Delayed::Job.count).by(1)

ActiveRecord add_column and update

In a migration, sometimes you want to add a new column, then update it do a new value.

def self.up
add_column :users, :plan_id, :integer
User.update_all("plan_id = 1")
end

FactoryGirl Callbacks

When setting up complex relationships with FactoryGirl, callbacks can help.

FactoryGirl Callbacks

Factory.define :user do |user|
user.name "Dusty Candland"
user.email "testing@testing.com"
user.phone "303-333-3333"
user.password "foobar"
user.password_confirmation "foobar"
end

Factory.define :user_with_subscription, :parent => :user do |user|
user.after_create{|u| Factory(:user_subscription, :user => u)}
end

Factory.define :user_subscription do |sub|
sub.first_name 'beta'
sub.last_name 'test'
sub.number '4111111111111111'
sub.expiration_year 2012
sub.expiration_month 1
sub.zip_code '90210'
sub.price 2.50
sub.group_limit 1
sub.message_limit 100
sub.association :plan
sub.user_id 1
end

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: