How to obtain a specification test for the model with field type enum - Mongoïde


EDIT: As per @max suggestion, I'm changing my model to use enum instead, however I can't test it for default state:

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

Works fine with the following code in the model:

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

But this part still fails:

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

Please note that I'm using Mongoid. I have this in my model spec:

OLD question - kept for reference?

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

And in my model I have this:

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

Yet is not working. I've tried removing the Mongoid bit but get the same error:

Failure/Error: it { 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

Note: I've also tried:

field :published,         type: Boolean,     default: false

And have added the following method in my model:

after_initialize :set_published, :if => :new_record?


def set_published
  self.published ||= false

But nothing seems to work. What am I missing?

If I understand correctly, you tried both Mongoid::Boolean and Boolean in your model, but not in the test.

Given the test failure message, I think it should be:

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

(and field :published, type: Mongoid::Boolean, default: false in your model)

Second problem:

Are you aware that have_field is to make tests on the views (the generated HTML), not to check that the field exists in the database?

We can't help you without the code of your views.

To check that the default value is draft, I'm not aware of any built-in Rails test method, so you should do it by hand. First create a new instance of your model, save it, and then check that the field published has draft value.

I'm not familiar with Rspec and the syntax you're using , but it should be something like (assuming you model is named Post):

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