我有一個描述病人(一包),它引用了目的地醫院和運送救護模型:代碼運行的控制檯,但不使用RSpec
class Packet < ActiveRecord::Base
belongs_to :hospital
belongs_to :provider
validates_presence_of :hospital_id
validates_presence_of :provider_id
end
class Hospital < ActiveRecord::Base
has_many :packets
end
class Provider < ActiveRecord::Base
has_many :packets
end
和我的RSpec規格:
require "rails_helper"
RSpec.describe Packet, :type => :model do
it "creates a new packet" do
hospital = Hospital.create(:name=>"Community Hospital")
provider = Provider.create(:name=>"Community Ambulance", :unit=>"Ambulance 3")
packet = Packet.new()
packet.hospital = hospital
packet.provider = provider
packet.save
end
end
RSpec失敗: 1)數據包創建新數據包 失敗/錯誤:packet.hospital = hospital ActiveModel :: MissingAttributeError: 無法寫未知att ribute hospital_id
我沒有得到的東西是我的測試的肉(「it」塊中的所有東西)在rails控制檯中運行良好,沒有錯誤。爲什麼我會在rspec測試中獲取未知屬性,但不在控制檯中?
完整的堆棧跟蹤: Garys-的MacBook空中-2:EMSPacket加里$ rspec的 ˚F
Failures:
1) Packet creates a new packet
Failure/Error: packet.hospital = hospital
ActiveModel::MissingAttributeError:
can't write unknown attribute `hospital_id`
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/attribute.rb:124:in `with_value_from_database'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/attribute_set.rb:39:in `write_from_user'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/attribute_methods/write.rb:74:in `write_attribute_with_type_cast'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/attribute_methods/write.rb:56:in `write_attribute'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/attribute_methods/dirty.rb:92:in `write_attribute'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/attribute_methods.rb:373:in `[]='
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/associations/belongs_to_association.rb:80:in `replace_keys'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/associations/belongs_to_association.rb:14:in `replace'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/associations/singular_association.rb:17:in `writer'
# /Users/gary/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-4.2.0/lib/active_record/associations/builder/association.rb:123:in `hospital='
# ./spec/models/packet_spec.rb:9:in `block (2 levels) in <top (required)>'
Finished in 0.14495 seconds (files took 7.49 seconds to load)
1例,1次失敗
Failed examples:
rspec ./spec/models/packet_spec.rb:4 # Packet creates a new packet
粘貼完整堆棧錯誤的跟蹤。 – tebayoso
嘗試在控制檯中運行相同的代碼,但使用測試環境:「RAILS_ENV =測試導軌控制檯」。如果失敗,那麼你沒有遷移你的數據庫。 「rake db:test:prepare」 – tebayoso
Jorge,謝謝。這是測試db – simusid