Ruby on rails 如何测试模型属性的有效性?

Ruby on rails 如何测试模型属性的有效性?,ruby-on-rails,rspec,Ruby On Rails,Rspec,我对仅允许字母数字字符(仅限字母和数字)的模型属性进行了验证 如何在不担心其他验证的情况下只测试这个专栏 validates :url, uniqueness: true, format: { with: /[^0-9a-z]/i, message: "Alphanumeric characters only." } 是否有一种方法仅针对此属性隔离测试?当测试格式时,您可以从;我认为您必须提供一些具有代表性的测试用例,以确保某些值是允许的,而其他值是不允许的: describe '

我对仅允许字母数字字符(仅限字母和数字)的模型属性进行了验证

如何在不担心其他验证的情况下只测试这个专栏

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

是否有一种方法仅针对此属性隔离测试?

当测试
格式时,您可以从;我认为您必须提供一些具有代表性的测试用例,以确保某些值是允许的,而其他值是不允许的:

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

为了唯一性,您可以从中使用。

当测试
格式时,您可以从中使用;我认为您必须提供一些具有代表性的测试用例,以确保某些值是允许的,而其他值是不允许的:

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

为了独特性,您可以使用。

可能值得指出的是,这里不需要shoulda matchers,它只是让规格更简洁一点。@AndyWaite,是的,这是真的,因此故意使用了“您可以使用…”的措辞。可能值得指出的是,shoulda matchers在这里不需要,它只是让规格更简洁一点。@AndyWaite,是的,这是真的,因此故意使用了“你可以使用…”的措辞。