Created
August 3, 2012 05:24
-
-
Save yesezra/3244678 to your computer and use it in GitHub Desktop.
Testing custom ActiveRecord validators with rspec and with_model
This file contains 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 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 |
Thanks!
Bless you for posting this. Life saver
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just what I was looking for. Tks.