-
-
Save kjavier/5054ec5e4a24fe1a82a0822062659d88 to your computer and use it in GitHub Desktop.
Testing custom ActiveRecord validators with rspec and with_model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ExcitementValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
unless value =~ /.*!/ | |
record.errors.add attribute, (options[:message] || "must end with an exclamation point") | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe ExcitementValidator do | |
with_model :post do | |
table do |t| | |
t.string :title | |
end | |
model do | |
validates :title, excitement: true | |
end | |
end | |
it "should be valid with an excited title" do | |
Post.new(title: 'My amazing day!').should be_valid | |
end | |
it "should be invalid with an unexcited title" do | |
Post.new(title: 'My lousy day.').should_not be_valid | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment