2016-08-01 65 views
1

我對僅允許字母數字字符(僅限字母和數字)的模型屬性進行驗證。如何測試模型屬性驗證正在工作?

我該如何測試這一列而不用擔心其他驗證?

validates :url, uniqueness: true, format: { with: /[^0-9a-z]/i, 
    message: "Alphanumeric characters only." } 

有沒有一種方法來隔離測試只是爲了這個屬性?

回答

0

當測試format時,可以使用Shoulda Matchers gem中的allow_values;我認爲你必須提供一些有代表性的測試用例來保證一定的值是允許的,而有些則沒有:

describe 'validations' do 
    describe 'for url' do 
    let(:valid_urls) do 
     ['Valid', 'URL', '3x4mp1e5'] 
    end 

    let(:invalid_urls) do 
     ['!nvalid', '|_|rl', 'example$'] 
    end 

    it 'allows valid URLs' do 
     expect(your_object).to allow_values(*valid_urls).for(:url) 
    end 

    it 'does not allow invalid URLs' do 
     expect(your_object).not_to allow_values(*invalid_urls).for(:url) 
     .with_message("Alphanumeric characters only.") 
    end 
    end 
end 

的唯一性,你可以使用validates_uniqueness_ofShoulda Matchers gem

+0

可能值得指出的是,shoulda-matchers在這裏並不重要,它只是使規格更簡潔一些。 –

+0

@AndyWaite,是的,這是真實的,因此故意「你應該使用...」措辭。 –