如何让具有枚举字段类型的模型通过规范测试 - Mongoid

How to get a spec test passing for model with enum field type - Mongoid

编辑:根据@max 的建议,我将我的模型改为使用枚举,但是我无法测试它的默认状态:

it { is_expected.to validate_inclusion_of(:status).to_allow("draft", "published") }

适用于模型中的以下代码:

validates :status,        :inclusion => { :in => ["draft", "published"] }

但是这部分还是失败了:

it { is_expected.to have_field(:status).with_default_value_of("draft") }

请注意,我使用的是 Mongoid。我的模型规格中有这个:

老问题 - 留作参考?

it { is_expected.to have_field(:published).of_type(Boolean).with_default_value_of(false) }

在我的模型中我有这个:

field :published,         type: Mongoid::Boolean,     default: false

还没有工作。我尝试删除 Mongoid 位但得到相同的错误:

Failure/Error: it { is_expected.to have_field(:published).of_type(Boolean).with_default_value_of(false) } Expected Post to have field named "published" of type Boolean with default value of false, got field "published" of type Mongoid::Boolean

注意:我也试过:

field :published,         type: Boolean,     default: false

并在我的模型中添加了以下方法:

after_initialize :set_published, :if => :new_record?

然后

private
def set_published
  self.published ||= false
end

但似乎没有任何效果。我错过了什么?

class Article
  include Mongoid::Document
  field :published, type: Boolean, default: false
end

require 'rails_helper'

RSpec.describe Article, type: :model do
  it { is_expected.to have_field(:published)
                      .of_type(Mongoid::Boolean)
                      .with_default_value_of(false) }
end

mongoid (4.0.2)mongoid-rspec (2.1.0).

上完美通过

但坦率地说,将布尔值用于模型状态并不是最佳选择。

如果您考虑博客 post 或文章,它可能是:

 1. draft
 2. published
 3. deleted
 4. ... 

在模型中添加 N 个开关很麻烦 - 一个很棒的解决方案是使用枚举。

先写规范:

RSpec.describe Article, type: :model do

  specify 'the default status of an article should be :draft' do
    expect(subject.status).to eq :draft
  end

  # or with rspec-its
  # its(:status) { should eq :draft }
end

然后将 gem "mongoid-enum" 添加到您的 Gemfile。

最后添加枚举字段:

class Article
  include Mongoid::Document
  include Mongoid::Enum
  enum :status, [:draft, :published]
end

枚举增加了所有这些令人敬畏的东西:

Article.published # Scope to get all published articles
article.published? # Interrogation methods for each state.
article.published! # sets the status

如果我没理解错的话,您在模型中尝试了 Mongoid::BooleanBoolean,但在测试中没有。

鉴于测试失败的信息,我认为应该是:

it { is_expected.to have_field(:published).of_type(Mongoid::Boolean).with_default_value_of(false) }

(以及您模型中的 field :published, type: Mongoid::Boolean, default: false

第二题:

你知道have_field是对视图(生成的HTML)进行测试,而不是检查该字段是否存在于数据库中吗?

没有您的观点代码,我们无法为您提供帮助。

要检查默认值是否为 draft,我不知道有任何内置的 Rails 测试方法,因此您应该手动执行。首先创建模型的新实例,保存它,然后检查发布的字段是否具有 draft 值。

我不熟悉 Rspec 和您使用的语法,但它应该类似于(假设您的模型被命名为 Post):

before {
    @post = Post.new
    # some initialization code if needed
    @post.save
}
expect(@post.published).to be("draft")