我有擔憂:關注測試失敗
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'
...
我試着在軌控制檯:
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 >
顯示你的工廠 –
看到工廠「肌肉」 – davydes
是的,它應該有工作。最近才添加'shape'屬性嗎?你也使用'春天'或什麼?我的賭注是緩存你的代碼,並沒有看到新的屬性。殺死所有彈簧,然後再試一次。 –