I am working on a project that has the following validation criteria in the "project" model:
validates :project_name,
presence: true,
format: { with: /\A[a-zA-Z\s_-]+\z/,
message: 'allows letters, spaces, underscores, and hyphens' }
validates :jira_id,
uniqueness: true,
presence: true,
format: { with: /\A[A-Z]+-[0-9]+\z/,
message: 'allows capitalized letters followed by a hyphen and numbers' }
validates :capacity,
presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :openings,
presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates_format_of :last_status_change_dt,
with: /\d{4}-\d{2}-\d{2}/,
message: 'must be formatted as YYYY-MM-DD',
on: :save
validates_presence_of :last_status_change_dt
The projects_controller:
def create
ActiveRecord::Base.transaction do
parameters = project_params.dup
parameters[:language_id] = get_language_id(params[:language_name]) if parameters[:language_id].nil?
@project = Project.new(parameters)
if @project.save
render json: @project, status: :created, location: @project
else
render json: @project.errors, status: :not_acceptable
raise ActiveRecord::Rollback
end
end
rescue ActiveRecord::ActiveRecordError
render json: { text: 'Project was not created' }, status: :internal_server_error
end
In the spec file, FactoryBot build and create functions are used.
In the tests right now, the validation is dependent on the project model, but I want to test the save function. How can I mock the save function to fail?