【问题标题】:rspec model test on string match regex adjustmentrspec 对字符串匹配正则表达式调整的模型测试
【发布时间】:2016-03-27 03:26:50
【问题描述】:

我在 rspec 中有以下测试

  it 'passes regex rules' do
    job = create(:job)
    job.valid?
    expect(job.title).to match(/\A[\w\d .,:-@]+\z/)
  end

这个正则表达式模式匹配模型模式。推荐的测试方法是什么,以确保未来开发人员的模型不会改变这种模式?

基本上我想测试不属于批准的条件:can only have 0-9, A-Z, periods, colons, hypens, underscores, and spaces. No new lines (enter keys)

更新

基于Generate random string based on Regex?,我决定现在使用(0..255).map(&:chr).select{|x| x != /\A[\w\d .,:-@]+\z/}.sample(5).join,这似乎可行,想法?

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    根据更新,我选择了以下内容:

    describe 'title' do
      let(:bad_string) { (0..255).map(&:chr).select{|x| x != /\A[\w\d .,:-@]+\z/}.sample(20).join }
    
      it 'should exist' do
        job = build(:job, title: nil)
        job.valid?
        expect(job.errors[:title].size).to eq(3)
      end
    
      it 'passes regex rules' do
        job = build(:job, title: bad_string)
        job.valid?
        expect(job.errors[:title].size).to eq(1)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2020-09-19
      相关资源
      最近更新 更多