关注测试失败

时间:2015-07-03 13:13:40

标签: ruby-on-rails rspec

我很担心:

module Anatomic
  extend ActiveSupport::Concern

  included do

    # Validations

    validates :alias, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[_a-z0-9]*\z/i }
    validates :name, presence: true, length: { maximum: 250 }
    validates :description, length: { maximum: 8000 }

    # Callbacks
    before_save { |anatomic| anatomic.alias = anatomic.alias.downcase }

  end
end

我的Muscle模型如下:

class Muscle < ActiveRecord::Base
  include Anatomic
end

模型Muscle拥有自己的属性shape。 关注测试如下:

require 'spec_helper'

shared_examples_for 'anatomic' do
  let(:model) { described_class.to_s.underscore.to_sym } # the class that includes the concern

  describe 'when create' do
    it 'should be valid by default' do
      anatomic = build(model)
      expect(anatomic).to be_valid
    end
  end    
end

测试模型Muscle

require 'rails_helper'

RSpec.describe Muscle, type: :model do
  it_behaves_like 'anatomic'
end

Muscle的工厂

FactoryGirl.define do
  factory :muscle do
    sequence (:alias) { |n| "alias#{n}" }
    name 'Example Name'
    description 'Example Description'
    shape 'long'
  end
end

Rspec因错误而崩溃:

1) Muscle behaves like anatomic when create should be valid by default
     Failure/Error: anatomic = build(model)
     NoMethodError:
       undefined method `shape=' for #<Muscle:0x000000076bcf90>
     Shared Example Group: "anatomic" called from ./spec/models/muscle_spec.rb:4
     # /home/john/.rvm/gems/ruby-2.2.1/gems/activemodel-4.2.1/lib/active_model/attribute_methods.rb:433:in `method_missing'
     # /home/john/.rvm/gems/ruby-2.2.1/gems/factory_girl-4.5.0/lib/factory_girl/attribute_assigner.rb:16:in `public_send'
     # /home/john/.rvm/gems/ruby-2.2.1/gems/factory_girl-4.5.0/lib/factory_girl/attribute_assigner.rb:16:in `block (2 levels) in object'
     # /home/john/.rvm/gems/ruby-2.2.1/gems/factory_girl-4.5.0/lib/factory_girl/attribute_assigner.rb:15:in `each'
     # /home/john/.rvm/gems/ruby-2.2.1/gems/factory_girl-4.5.0/lib/factory_girl/attribute_assigner.rb:15:in `block in object'
     ...

我在rails console中尝试过:

2.2.1 :001 > m = Muscle.new alias: 'test', name: 'Example test', shape: 'long'
 => #<Muscle id: nil, alias: "test", name: "Example test", description: nil, shape: "long", created_at: nil, updated_at: nil> 
2.2.1 :002 > m.save!
   (0.2ms)  begin transaction
  Muscle Exists (0.1ms)  SELECT  1 AS one FROM "muscles" WHERE LOWER("muscles"."alias") = LOWER('test') LIMIT 1
  SQL (0.3ms)  INSERT INTO "muscles" ("alias", "name", "shape", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["alias", "test"], ["name", "Example test"], ["shape", "long"], ["created_at", "2015-07-03 13:10:01.305612"], ["updated_at", "2015-07-03 13:10:01.305612"]]
   (159.9ms)  commit transaction
 => true 
2.2.1 :003 > 

1 个答案:

答案 0 :(得分:0)

您的控制台正在使用您的development数据库,而您的测试正在使用您的test数据库。我建议你的测试数据库在shape表中没有muscles字段。运行此命令以重置测试数据库:

bin/rake db:reset db:setup RAILS_ENV=test