我在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
这似乎有效,想法?
答案 0 :(得分:0)
根据更新,我选择了以下内容:
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