Are you eager to elevate your security skills and safeguard your applications
against cyber threats? I created a Rails Security course is designed
specifically for developers like you who aim to build robust, secure Rails
applications!
Buy my course: Security for Rails Developers.
I often get the question from new rubyist "How should I test my model validations in Rails?". A simple example is when we have a `Post` model with two required fields:
Buy my course: Security for Rails Developers.
# app/models/post.rb
class Post < ActiveRecord::Base
validates_presence_of :title, :body
end
# test/models/post_test.rb
require 'test_helper'
class PostTest < ActiveSupport::TestCase
test "should not save post without title or body" do
post = Post.new
assert_not post.save
post.title = 'Test'
assert_not post.save
post.body = 'Test body'
assert post.save
end
end
# test/models/post_test.rb
test "should have the necessary required validators" do
post = Post.new
assert_not post.valid?
assert_equal [:title, :body], post.errors.keys
end
# app/models/post.rb
class Post < ActiveRecord::Base
validates_presence_of :title, :body
validates :score, numericality: true, allow_blank: true
end
# test/models/post_test.rb
test "should have numeric score" do
post = Post.new(title: 'test', body: 'test body', score: 'test')
assert_not post.valid?
assert_equal ["is not a number"], post.errors.messages[:score]
end
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!