Bazley
Bazley

Reputation: 2847

Failing user validation with nested attributes and polymorphic association

This simple validation test is failing:

require 'test_helper'
class UserTest < ActiveSupport::TestCase
  def setup
    @user = User.new(name: "Example User", 
                     email: "[email protected]", 
                     character_attributes: {callsign: "example"},
                     password: "foobar", 
                     password_confirmation: "foobar"
                     )
  end

  test "should be valid" do
    assert @user.valid?, "#{@user.errors.messages}"
  end

end

...with this message: character.sociable_id"=>["can't be blank"]

I don't understand why the user creation in UserTest is failing to make a valid User.

Each User has_one :character and each Character belongs_to a User.

The User model: User.rb:

class User < ActiveRecord::Base

  attr_accessor :remember_token, :activation_token, :reset_token
  has_one  :character, as: :sociable, dependent: :destroy
  accepts_nested_attributes_for :character
  has_secure_password
  before_validation do
    self.create_character unless character
  end
  before_save do
    self.email.downcase!
  end
  before_create :create_activation_digest
  validates :name, presence: true,
                   length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence:   true,
                    format:     { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 6 }, allow_blank: true
  validates :character, presence: true
  .
  .
end

The Character model: Character.rb:

class Character < ActiveRecord::Base
  belongs_to :sociable, polymorphic: true
  has_many   :posts, dependent: :destroy
  before_save do
    self.callsign.downcase!
  end
  validates :sociable_id, presence: true
  VALID_CALLSIGN_REGEX = /\A[a-z\d\-.\_]+\z/i
  validates :callsign, presence:   true,
                       length:     { maximum: 20 },
                       format:     { with: VALID_CALLSIGN_REGEX },
                       uniqueness: { case_sensitive: false }

end

Upvotes: 0

Views: 94

Answers (1)

Shamsul Haque
Shamsul Haque

Reputation: 2451

It should be:-

test "should be valid" do
  assert @user.valid? , "#{@user.errors.messages}"
end

Upvotes: 1

Related Questions