开发者

Best practice: Ruby/Rails Rspec regex testing

开发者 https://www.devze.com 2023-01-16 17:46 出处:网络
Could you tell me how to test regex-code correctly? I test my user-login attribute with following code:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消