RSpec未显示正确的默认值

时间:2016-01-19 19:09:09

标签: ruby-on-rails rspec

我有一个名为Score的模型的规范,其代码如下:

# == Schema Information
#
# Table name: scores
#
#  id                 :integer          not null, primary key
#  score              :integer          default(0), not null
#  exam_id            :integer
#  user_id            :integer
#  questions_answered :integer          default(0), not null
#  created_at         :datetime
#  updated_at         :datetime
#

require 'rails_helper'

RSpec.describe Score, type: :model do
  describe "when a new score is initialized" do
    before { @new_score = Score.new }

    it "should have questions_answered value of 0" do 
      expect(@new_score.questions_answered).to eq 0
    end
  end
end

此测试的输出如下:

Failures:

1) Score when a new score is initialized should have questions_answered value of 0
 Failure/Error: expect(@new_score.questions_answered).to eq 0

   expected: 0
        got: nil

   (compared using ==)

正确的架构信息位于该规范的顶部,如您所见,questions_answered字段的默认值为0。

我可以看到,在保存对象之前,可能不会设置此默认值,因为默认值是在数据库上设置的。但是,在控制台中,如果我输入s = Score.new,这是我收到的输出:

2.2.0 :001 > s = Score.new
=> #<Score id: nil, score: 0, exam_id: nil, user_id: nil, questions_answered: 0, created_at: nil, updated_at: nil> 

正如您可以清楚地看到的那样,Score.new返回一个对象,其默认值正确设置为0.那么为什么规范失败?

0 个答案:

没有答案