Skip to content

Commit

Permalink
Add validation to period fields and feedback in form
Browse files Browse the repository at this point in the history
  • Loading branch information
paulohenrique-gh committed Mar 24, 2024
1 parent 71cadfe commit b5ee3b6
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
8 changes: 8 additions & 0 deletions app/components/period_form_component.html.erb
@@ -1,3 +1,11 @@
<% if @period.errors.any? %>
<ul>
<% @period.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<%= form_with model: @period do |f| %>
<div>
<%= f.label :name %>
Expand Down
7 changes: 5 additions & 2 deletions app/controllers/periods_controller.rb
Expand Up @@ -11,9 +11,12 @@ def new

def create
@period = Period.new(period_params)
@period.save
if @period.save
redirect_to @period, notice: t('.success')
end

redirect_to @period, notice: t('.success')
flash[:alert] = 'Não foi possível cadastrar o período'
render :new, status: :unprocessable_entity
end

private
Expand Down
4 changes: 2 additions & 2 deletions app/models/period.rb
@@ -1,7 +1,7 @@
class Period < ApplicationRecord
validates :name, presence: true
validates :name, :start_year, presence: true

validates :start_year, :end_year, numericality: { greater_than: 1 }
validates :start_year, :end_year, numericality: { greater_than: 1 }, allow_blank: true
validates :end_year, comparison: { greater_than_or_equal_to: :start_year }

validates :name, length: { maximum: 50 }
Expand Down
17 changes: 17 additions & 0 deletions spec/system/periods/admin_registers_period_spec.rb
Expand Up @@ -18,6 +18,23 @@
expect(Period.count).to eq 1
expect(page).to have_content 'Período cadastrado com sucesso.'
end

it 'with blank fields' do
user = create(:user, role: :admin)

login_as user
visit new_period_path
fill_in 'Nome', with: ''
fill_in 'Ano de início', with: ''
fill_in 'Ano de término', with: ''
click_on 'Salvar'

expect(Period.count).to eq 0
expect(page).to have_content 'Não foi possível cadastrar o período'
expect(page).to have_content 'Nome não pode ficar em branco'
expect(page).to have_content 'Ano de início não pode ficar em branco'
expect(page).to have_content 'Ano de término não pode ficar em branco'
end
end

context 'User role' do
Expand Down

0 comments on commit b5ee3b6

Please sign in to comment.