← Back to Upcase

Unit Testing Form Objects


(Dolph Mullen) #1

I’m using a customer_registration form object to handle the logic of creating a customer, with its credentials, personal information, and billing information. I’m curious how I would go about testing the register! method? I’m handling form validation in this object, so should the persistence logic be deferred to the models that are actually taking care of that?

class CustomerRegistration
  include ActiveModel::Model

  ...

  def register!
    if valid?
      persist!
    else
      false
    end
  end

  private
  def persist!
    # Persist the data from the form
  end
end

I considered having a little test to make sure it returns true if valid? is true, which just entails stubbing valid?, but that seems a little too simple. Any suggestions?


(Guirec Corbel) #2

You can check the spec for ActiveForm-rails here. Please take a look at this gem and let me know if it does not do everything you want.


(Geoff Harcourt) #3

This might be a violation of stubbing the SUT, but I think as long as you also have explicit unit tests for the validation logic that it’s fine to have an isolated test that calls #persist! when #valid? returns true.


(Dolph Mullen) #4

Thanks for the input! @Guirec_Corbel that gem seems nice, but I really appreciate you passing along the specs. I now realize how silly I was being.