Rails Unit Test multi-array params

While writing some tests the other day, I came across a little bit of a stump. I have an action that required the use of a multi-dimensional param such as:

param[:user][:name]

This is exactly what I was doing, but you get the picture. I could have easily changed it to a single array, but that not the point. The solution in this example, would be to nest your hash in the test such as:

def test_should_do_something
  post :create, :some_object=>{
    :name=>'Bob'
  }, :user=>{ :name=>'Something' }
end

Override default find conditions for model

Here is a little trick I use when I want to override a find method for a model, instead of adding the conditions option to my association. While I don’t think you should avoid using the conditions options in your associations, this will provide an alternative:

class ModelName < ActiveRecord::Base
  def self.find(*args)
    with_scope(:find=>{ :conditions=>LIMIT_CONDITION }) do
      super(*args)
    end
  end
end

Basically what is happening, is that you are overriding the default find function for a model, and wrapping its own find method with a with_scope call. So now every time you call Model.find(:all) or whatever options you want, it will execute it under that scope, with the conditions you specify.

%d bloggers like this: