I have a simple CRUD app with some basic validations for a Commodity model. The tests for those pass. OK, now I need to test against having no spaces, or more than one word for its name. I tested the below in console and it seemed to work so reading up on the rails guides on validations I wrote a custom validation below. Unfortunately running my tests, all fail now because it cannot create a commodity because it fails due to the custom validation I wrote. I’ve tried many different combinations of incorprating the validator starting with Railscasts #211 by combining it into the validates call. It’s probably something simple but if I yank out the call to the validator then the other basic tests pass. The error is: Validation failed: Name must be a single word (ActiveRecord::RecordInvalid)
require_relative 'commodity_name_validator'
class Commodity < ActiveRecord::Base
attr_accessible :description, :name
has_many :prices
before_save { |commodity| commodity.name.capitalize! }
validates :name, presence: true, length: { minimum: 4 }
validate :commodity_name_validations
end
class CommodityNameValidator < ActiveModel::Validator
def validate(record)
if record.name.split(" ").length <= 1
record.errors[:base] << "Name must be a single word"
end
end
end
thnx, sam
It appears this ‘stomp’ is due to cucumber throwing errors earlier when it encounters a basic error in this case. Thanks to @jorendorff pointing out that replacing my <= 1 to != 1 made this test pass and those previous to pass as well. I don’t know if it’s ruby’s reflection or what that causes previous passing tests to error out, I’m speaking out of ignorance. I just know that cucumber, at least, will throw errors that mislead to the real cause.