Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

PIVOTAL LABS
Standup 10/15/2008: this_method; dynamically creating tables for testing
  • Where am I? — Ever need to find the name of the method you are currently within? Here’s a this_method method! The magic is in the REGEX, of course.
module Kernel
  private
  def this_method
    caller[0] =~ /`([^']*)'/ and $1
  end
end
  • One project wanted to test a very ActiveRecord-specific Module in an isolated, generic way. After spending time researching techniques of mocking and stubbing the many, many ActiveRecord methods that would be touched, they decided to just dynamically create an ActiveRecord and a DB Table for it on the fly! They even used single table inheritance (STI)
  describe "MyMagicModule Mixin" do
    before(:all) do
      ActiveRecord::Base.connection.create_table "some_base_models",
                                                   :force => true do |t|
        t.string   "name"
        t.string   "type"
        t.integer  "some_model_b_id", :limit => 11
      end
    end

    after(:all) do
      ActiveRecord::Base.connection.drop_table "some_base_models"
    end


    class SomeBaseModel < ActiveRecord::Base;end

    class SomeModelA < SomeBaseModel
      include MyMagicModule

      belongs_to: :some_model_b
    end

    class SomeModelB < SomeBaseModel
      include MyMagicModule
    end

    it 'should use special belongs_to stuff from MyMagicModule' do
       model_a = SomeModelA.create!(
                        :name=> "Model A",
                        :some_model_be => SomeModelB.create!(:name => "Model B"))
       # test the functionality from MyMagicModule
    end
  end

Comments
  1. “Where Am I?” – seems *very* useful when debugging meta-programming soup.

  2. Pat Nakajima says:

    Hey, for dynamically creating activerecord models, take a look at my acts_as_fu project: [github.com/nakajima/acts_as_fu](http://github.com/nakajima/acts_as_fu). It does pretty much the same thing you showed, just a bit more concisely.

  3. Joe Moore says:

    @Pat — I just used [acts_as_fu](http://github.com/nakajima/acts_as_fu) on a new project and it is the new hotness! Thanks!

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *