运行rspec + factory_girl时出错:未定义的方法&#39; some_factory =&#39;对于#<class instance =“”> </class>

时间:2014-10-25 14:00:55

标签: rspec factory-bot shoulda ruby-on-rails-4.1

我在这里有点新手......我无法找到明显的解决方案来解决rspec问题。我试图测试作用域唯一性验证(请参阅下面的character_class_spec.rb中的test)。我假设错误告诉我它无法找到character_class工厂?无论如何,我为此挣扎着数据和测试设置。非常感谢输入/帮助。

运行&#34; rspec spec&#34; 时出现

错误

1)CharacterClass      失败/错误:let(:char_class){build(:character_class)}      NoMethodError:        未定义的方法character_class=' for #<CharacterClass:0x007fa1ea049dc0> # ./spec/models/character_class_spec.rb:9:in阻止(2级)&#39;      #./spec/models/character_class_spec.rb:14:in块中的“块(2级)”

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架构定义

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

环境

红宝石2.1.2 rails 4.2.0.beta2

Gemfile片段

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

1 个答案:

答案 0 :(得分:0)

我想通了!问题是我的character_class工厂错了。我使用“character_class”而不是“class_name”作为其中一个属性。错误告诉我它找不到setter“character_class =”,因为这是CharacterClass的无效类定义。非常感谢帖子显示通过rails控制台调用FactoryGirl(Single Table Inheritance with Factory Girl in Rails)!