Manually setting id in Rails 2

Posted by Tim Connor Fri, 20 Oct 2006 00:12:00 GMT

In testing DynamicScaffoldResource, I have been working on sort of mocking/overloading ActiveRecord so that it doesn’t touch the DB, so I can minimize how much it depends on the root Rails environment to test, since it’s a plug-in.

class Resource < ActiveRecord::Base
  def self.columns() @columns ||= []; end
  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
  end
  def self.find(param)
    return param == :all ? [Resource.new(:id => 1, :name => 'bob')] : Resource.new(:id: => 1, :name => 'bob')
  end

  column :id,            :integer
  column :name,          :string

  validates_presence_of :name
end

Well Rails treats the id as a special field, since it is. I tried letting it implicitely add it, and explicitely as above, but there was no way I seemed to be able to set it manually and access it (maybe the problem is prior to a save?), so my edit named route in the view wouldn’t choke (the show path had no problem with the nil, which I might not have caught for a while). While there is probably some way to open up access to the id column, this mailing list post opened up an alternative that works, just use:


Resource.new{ |m| m.id = 1; m.name = ‘bob’ }

Comments

Leave a comment

  1. Avatar
    James 3 days later:

    Have you tried using Mocha ?

  2. Avatar
    Tim Connor 5 days later:

    Nah, I was tempted too, Joe, but these first couple plugins are very much learning experiences, so I wanted to try manually, first. I also decided I didn’t want to learn another piece on top of ruby, Rails, REST, and TDD, yet, but instead stick with getting the basics of those down.

    I just needed to redefine a couple functions in AR so it didn’t touch the DB. The standard tests from the generated scaffold_resource are fairly basic, and those are what I was porting over. The trickiest parts for me currently are fundamental stuff that I should know before moving into further abstraction.

    I definitely will be considering playing with Mocha, ZenTests’ separation of view and controller tests, and Selenium, at some point.

Comments