Assume the following ActiveRecord::Base class:
#./app/models/army_list.rb class ArmyList < ActiveRecord::Base belongs_to :game_system validates :name, :presence => true validates :points, :numericality => true validates :game_system, :presence => true end
I was just pulling my hair out over this spec I was writing to make sure all my validations were working properly:
#./spec/models/army_list_spec.rb describe ArmyList do it "should be valid" do ArmyList.new(:name => "Name", :points => 1500, :game_system => Factory(:game_system)).should be_valid end end
Changing it from the constructor method to the block method works however:
#army_list_spec.rb describe ArmyList do it "should be valid" do ArmyList.new do |al| al.name = "Name" al.points = 1500 al.game_system = Factory(:game_system) end .should be_valid end end
Now that I've solved this problem it makes sense. The ActiveRecord::Base documentation for #new states
[...] valid attribute keys are determined by the column names of the associated table – hence you can’t have attributes that aren’t part of the table columns.
Because the column name is actually game_system_id
it doesn't make sense that I'd be assigning game_system
- an attribute that doesn't exist on the table - by using this form of the constructor.