Search code examples
ruby-on-railsruby-on-rails-3rspecrspec-rails

Testing association through aliases


I'm new to TDD and Rails. I'm trying to test an 'aliased' association (don't know if this is a valid term).

My test:

it 'an order should always have a customer' do
  o = Order.new
  o.should_not be_valid
end

My model:

class Order < ActiveRecord::Base
  belongs_to :customer, :class_name => Person
  validates_associated :customer
end

I don't know if validates_associated does what It implies. My test still counts orders with 'custumer_id: nil' as valid.

The Person model:

class Person < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :middle_name
  validates_presence_of :first_name, :last_name

  has_many :addresses
  has_many :orders, :as => :customer
end

I want to make sure that every Order saved has an associated custumer (a Person object). Am I missing something?


Solution

  • validates_associated only tells the Model that validations should be run on associated objects as well (have a look at the docs here). You still need to add a validation on Order. Have a look at this SO question. I could be wrong, but I think it will point you in the direction of what you're looking for.