Best practice: Ruby/Rails Rspec regex testing
Could you tell me how to test regex-code correctly?
I test my user-login attribute with following code:
# user.rb
class User < ActiveRecord::Base
#...
validates_format_of :login开发者_运维技巧, :with => /^[a-zA-z0-9_.]{3,18}$/
end
# user_spec.rb
describe User do
before(:each) do
@user = Factory.build(:user)
@user.save
end
subject { @user }
it { should be_valid }
it { should_not allow_value("b lah").for(:login) }
it { should_not allow_value("bälah").for(:login) }
it { should_not allow_value("b@lah").for(:login) }
it { should_not allow_value("bülah").for(:login) }
it { should_not allow_value("bßlah").for(:login) }
it { should_not allow_value("b!lah").for(:login) }
it { should_not allow_value("b%lah").for(:login) }
it { should_not allow_value("b)lah").for(:login) }
# ....
# Shall I test here every special sign????
end
But it seems very redundant and not secure.... Is there a best practice? Thx!
You're not really testing your model here, you're testing your regex. It's not quite the same thing. Also, you're testing the same aspect of your regex, that it only allows [a-zA-z0-9_.], again and again. If you want to apply different tests, test different aspects of it, eg with "lo" (<3 chars) or "12345678901234567890" (>18 chars).
Also, if you wanted to dry it up you could do something like
invalid_logins = ["b lah","bälah","b@lah","bülah","bßlah","b!lah","b%lah","b)lah"]
invalid_logins.each do |s|
it { should_not allow_value(s).for(:login) }
end
精彩评论