loading...

re: How to test that you are creating a record without using the database VIEW POST

TOP OF THREAD FULL DISCUSSION
re: class Blog validates :title, presence: true end # no validation Blog.save(attrs) # has validation blog = Blog.new blog.save(attrs) Insta...

I've got the answer. The validation works but seems not easy to test.

!@blog.id.nil? #this works, any better code?

I can plan two stages test. First stage don't test validation. In second integration test I can use model test to do validation test. Do you agree with me? :)

I would test the validation part, just as I said in the comment... This
is because, most of the time I don't put validation code in the Rails
models.

I would put the behavior in a kind of form object, in fact, you could use
ActiveModel if you want...

Two possible solutions could be...

Without ActiveModel...

module Blog
  def self.add_post(attrs, store)
    form = Form.new(attrs)

    if form.title.nil?
      form.add_error!(:title, "can't be blank")
      ErrorStatus.new(form)
    else
      store.create(form.to_h)
      SuccessStatus
    end
  end

  class Form
    attr_reader :title, :body, :errors

    def initialize(params = {})
      @title = params["title"]
      @body = params["body"]
      @errors = {}
    end

    def to_h
      { title: title, body: body }
    end

    def add_error!(field, error)
      errors[field] ||= []
      errors[field] << error
    end
  end

  class ErrorStatus
    attr_reader :form

    def initialize(form)
      @form = form
    end

    def success?
      false
    end
  end

  class SuccessStatus
    def self.success?
      true
    end
  end
end

With ActiveModel...

module Blog
  def self.add_post(attrs, store)
    form = Form.new(attrs)

    if form.valid?
      store.create(form.to_h)
      SuccessStatus
    else
      ErrorStatus.new(form)
    end
  end

  class Form
    include ActiveModel::Model
    attr_accessor :title, :body
    validates_presence_of :title

    def to_h
      { title: title, body: body }
    end
  end

  # ...
end

Looks nice, thanks.

Then you don't write rails AR validation, is this true?

Is really rare... but I do use ActiveModel for form objects very often

Code of Conduct Report abuse