0

I'm a bit of a newbie here.. I can't find an obvious solution to an rspec failure. I'm trying to test a scoped uniqueness validation (see test in character_class_spec.rb below). I'm assuming the error is telling me that it can't find the character_class factory?? Regardless, I'm struggling with data and test setup for this. Input/help would be greatly appreciated.

error from running "rspec spec"

1) CharacterClass Failure/Error: let(:char_class) { build(:character_class) } NoMethodError: undefined method character_class=' for #<CharacterClass:0x007fa1ea049dc0> # ./spec/models/character_class_spec.rb:9:inblock (2 levels) in ' # ./spec/models/character_class_spec.rb:14:in `block (2 levels) in '

character_class_spec.rb

require 'spec_helper'

RSpec.describe CharacterClass, :type => :model do

  it "has a valid factory" do
    expect { Factory.build(:character_class).to be_valid }
   end

  let(:char_class) { build(:character_class) }

  it { expect(char_class).to validate_uniqueness_of(:level).scoped_to(:class_name, :character_id)}

  # it "does not allow duplication of records" do
  #   expect { FactoryGirl.create(:character_class, level: 1, class_name: "Dwarf").to be_valid }
  #   expect { FactoryGirl.create(:character_class, level: 1, class_name: "Dwarf").to be_valid }
  # end

end

character_class.rb model

class CharacterClass < ActiveRecord::Base
  belongs_to :character

  validates :class_name, presence: true
  validates :character_id, presence: true
  validates :level, presence: true

  validates :level, uniqueness: { :scope => [:class_name, :character_id],
                        message: "should have unique level per class name" }
end

character_class schema definition

class CreateCharacterClasses < ActiveRecord::Migration
  def change
    create_table :character_classes do |t|
      t.string :class_name, null: false
      t.integer :level, null: false;
      t.belongs_to :character, index: true, null: false;

      t.timestamps null: false
    end
    add_index :character_classes, [:character_id, :class_name, :level], :name =>      'ind_chclass_on_ch_id_and_chname_and_level', :unique=>true
  end
end

Environment

ruby 2.1.2 rails 4.2.0.beta2

Gemfile snippet

group :test do
  gem 'minitest'
  gem 'faker'
  gem 'capybara'
  gem 'guard-rspec'
  gem 'launchy'
  gem 'shoulda-matchers', require: false
end
Holly
  • 9
  • 4

1 Answers1

0

I figured it out!!! The problem was that my character_class factory was wrong. I was using "character_class" instead of "class_name" for one of the attributes. The error was telling me that it couldn't find the setter "character_class=" as this was an invalid class definition for CharacterClass. Many thanks to a post that showed calling FactoryGirl through the rails console (Single Table Inheritance with Factory Girl in Rails)!

Community
  • 1
  • 1
Holly
  • 9
  • 4