# frozen_string_literal: true require 'test_helper' require 'upgrow/action' require 'upgrow/input' module Upgrow class ActionTest < ActiveSupport::TestCase class SampleAction < Action expose :user def perform @user = 'volmer' end end class SubSampleAction < SampleAction expose :article def perform super @article = 'The Hobbit' end end class EmptyAction < SubSampleAction def perform; end end class FailedAction < SampleAction def perform super failure(:error1, :error2) end end class SampleInput < Input attribute :name validates :name, presence: true end test '.exposures is empty by default' do assert_empty Action.exposures end test '.expose sets the exposures in the Action Result class' do assert_equal([:user], SampleAction.exposures) end test '.expose includes inherited exposures' do assert_equal([:user, :article], SubSampleAction.exposures) end test '#perform raises NoMethodError error when it is not implemented' do assert_raises(NoMethodError) do Action.perform end end test '#perform returns the exposed instance variables' do result = SubSampleAction.new.perform assert_equal 'volmer', result.user assert_equal 'The Hobbit', result.article assert_empty result.errors end test '#perform returns nil for each exposed instance variable that is not set' do result = EmptyAction.new.perform assert_nil result.user assert_nil result.article assert_empty result.errors end test '#perform returns a Result with errors when #failure is called' do result = FailedAction.new.perform assert_equal 'volmer', result.user assert_equal [:error1, :error2], result.errors end test '#failure throws a failed Result with the given errors' do action = SampleAction.new caught = true result = catch(:failure) do action.failure(:error) caught = false end assert caught assert_equal([:error], result.errors) assert_nil result.user end test '#failure converts Active Model Errors into an Array of Errors' do action = SampleAction.new input = SampleInput.new(name: '') input.valid? result = catch(:failure) { action.failure(input.errors) } assert_nil result.user assert_predicate result.errors, :one? error = result.errors.first assert_equal :blank, error.code assert_equal :name, error.attribute assert_equal "Name can't be blank", error.message end end end