rspec希望在通过post创建后更改记录值

时间:2015-02-01 01:20:13

标签: ruby-on-rails rspec

我有这个例子来通过传递的post创建一条新记录

describe 'POST create' do
  let(:schedule_child) { FactoryGirl.create(:schedule_child) }
  let(:post_queue) { post :create, schedule_child_id: schedule_child.id, format: :js }

  it { expect{post_queue}.to change(PatientQueue, :count).by(1) }
end

我有一个属性PatientQueue.queue_number,每次添加新记录时都会增加1。现在我想看看这些属性是否已经改变。

it { expect{post_queue}.to change(PatientQueue, :queue_number).by(1) }

但这是我得到的

NoMethodError: undefined method `queue_number' for #<Class:0x0000000849e780>

我应该如何正确地写出来?

==更新==

模型PatientQueue

class PatientQueue < ActiveRecord::Base
  # Validations
  validates :patient, :schedule_child, presence: true
  validate :is_not_exist

  # Relations
  belongs_to :schedule_child
  belongs_to :patient

  before_create :insert_queue_number

  def is_exist?
    PatientQueue.find_by_schedule_child_id_and_patient_id(schedule_child_id, patient_id).present?
  end

  private
    def insert_queue_number
      last_id = PatientQueue.where("schedule_child_id = ?", self.schedule_child_id).count
      self.queue_number = last_id + 1
    end

    def is_not_exist
      errors.add(:schedule_child, :is_exist) if is_exist?
    end

end

1 个答案:

答案 0 :(得分:2)

PatientQueue是一个activerecord类,它有一个方法count

post_queue是该类的一个实例,其方法为queue_number

该类与实例的方法不同,因此您可以像change(post_queue, :queue_number).by(1)

那样编写测试

但是,测试有点难以理解,您能告诉我们您的数据模型关系吗?如果PatientQueue has_many schedule_child,您可能只想使用rails cache_counter? http://www.elegantruby.com/Tutorials/2013/01/25/adding-a-counter-cache-for-fun-and-profit/