Shoulda: Test validates_presence_of :on => :update

倖福魔咒の 提交于 2019-12-10 14:28:21

问题


I'm using Shoulda in combination with Test::Unit on one of the projects I work on. The issue I'm running into is that I recently changed this:

class MyModel < ActiveRecord::Base
  validates_presence_of :attribute_one, :attribute_two
end

to this:

class MyModel < ActiveRecord::Base
  validates_presence_of :attribute_one
  validates_presence_of :attribute_two, :on => :update
end

Previously, my (passing) tests looked like this:

class MyModelTest < ActiveSupport::TestCase
  should_validate_presence_of :attribute_one, :attribute_two
end

As far as I can tell, there is no parameter to should_validate_presence_of that will cause this test to continue to pass with the changes specified above. Short of abandoning Shoulda when testing the requirement of :attribute_two, is there any way around this?


回答1:


In that past I have just used a small custom should block to get around this problem:

should "require :attr_two on update" do
  mm = Factory(:my_model)
  mm.attr_two = nil
  mm.save
  assert_equal false, mm.valid?
  assert_equal("can't be blank", mm.errors.on(:attr_two))
 end

Hopefully shoulda will keep improving by allowing further AR validation options in the future. Let me know what you think, cheers.




回答2:


What about something like this? (for shoulda-matchers-3.1.1)

subject { FactoryGirl.build(:your_model) }
it { is_expected.to validate_presence_of(:attribute_one) }
it { is_expected.to validate_presence_of(:attribute_two).on(:update) }



回答3:


In Rspec you can do the following:

describe MyModelTest do
  describe "validations" do
    should_validate_presence_of :attribute_one

    context "on update" do
      subject { FactoryGirl.create(:my_model_test) }

      should_validate_presence_of :attribute_two
    end
  end
end



回答4:


I have tried a solution similar to what tsdbrown suggested. This type of test passes when I have:

validates_presence_of :attr_two

But the test fails if I change the model to:

validates_presence_of :attr_two, :on => :save

It fails because the :attr_two error is [] instead of ["can't be blank"]



来源:https://stackoverflow.com/questions/2009159/shoulda-test-validates-presence-of-on-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!