我有一个描述病人(一包),它引用了目的地医院和运送救护模型:代码运行的控制台,但不使用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