【问题标题】:Shoulda rspec matchers :on => :create应该 rspec 匹配器 :on => :create
【发布时间】:2010-06-28 16:07:39
【问题描述】:

我正在使用一些 Shoulda rspec 匹配器来测试我的模型,其中之一是:

describe Issue do
  it { should_not allow_value("test").for(:priority) }
end

我的问题是我在模型中的验证看起来像这样:

validates_format_of :priority, :with => /^(Low|Normal|High|Urgent)$/, :on => :update

所以当运行这个测试时,我得到:

1) 'Issue should not allow priority to be set to "test"' FAILED
   Expected errors when priority is set to "test", got errors: category is invalid (nil)title can't be blank (nil)profile_id can't be blank (nil)

验证没有被触发,因为它只在更新时运行,我如何在更新和创建时使用这些应该匹配器?

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec shoulda


    【解决方案1】:

    我认为应该更好地处理这个问题。我遇到了这个问题,因为我只想在创建新用户时对我的用户模型运行唯一性验证检查。在更新时执行数据库查询是浪费,因为我不允许更改用户名:

    validates :username, :uniqueness => { :case_sensitive => false, :on => :create },
    

    幸运的是,您可以通过明确定义“主题”来解决这个问题:

      describe "validation of username" do
          subject { User.new }
          it { should validate_uniqueness_of(:username) }  
      end
    

    这样它只在一个新实例上进行测试。对于您的情况,您可能只需将主题更改为已保存在数据库中的内容,并设置所有必要的字段。

    【讨论】:

    • 谢谢@endium。同样,subject { FactoryGirl.create(:user) } 可用于测试 on: :update-only 验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多