Skip to content

Instantly share code, notes, and snippets.

@oniram88
Last active July 25, 2023 04:32
Show Gist options
  • Save oniram88/4d516612535bf8c0f6f2fcee5028b290 to your computer and use it in GitHub Desktop.
Save oniram88/4d516612535bf8c0f6f2fcee5028b290 to your computer and use it in GitHub Desktop.
validated? example
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :projects, force: true do |t|
t.string :name
end
create_table :step1s, force: true do |t|
t.integer :project_id
t.string :category
end
create_table :step2s, force: true do |t|
t.integer :project_id
t.string :product
end
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
attr_reader :is_validated
alias_method :validated?, :is_validated
after_initialize -> { @is_validated = false }
after_validation -> { @is_validated = true }
end
class Project < ApplicationRecord
has_one :step1
has_one :step2
validates_associated :step1, unless: -> { name.blank? }
validates_associated :step2, if: -> { step1.validated? && step1.valid? }
validates :name, presence: {allow_blank: false}
after_initialize -> { build_step1 if step1.nil? }
after_initialize -> { build_step2 if step2.nil? }
end
class Step1 < ApplicationRecord
validates :category, presence: true
end
class Step2 < ApplicationRecord
validates :product, presence: true
end
class Simulation < Minitest::Test
def test_multi_step
# first time on the new form of the model with controller/view
project = Project.new
assert project.invalid?
refute project.step1.validated?
assert project.step1.errors.empty?
refute project.step2.validated?
# second time on the new form of the model with controller/view
project.name = "project name"
assert project.invalid?
assert project.step1.validated?
assert project.step1.errors.any?
assert project.step2.errors.empty?
refute project.step2.validated?
# third time on the new form of the model with controller/view
assert project.step1.category = "category name"
assert project.invalid?
assert project.step1.validated?
assert project.step1.errors.empty?
assert project.step2.validated?
assert project.step2.errors.any?
project.step2.product = "product name"
assert project.valid?
# now we can save
assert project.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment