如何仅在使用rspec更新时测试模型对象的有效性?

时间:2012-07-08 23:38:52

标签: ruby-on-rails ruby-on-rails-3 unit-testing rspec rspec2

我有一个像这样的个人资料模型;

class Profile < ActiveRecord::Base
  attr_accessible :first_name, :last_name
  belongs_to :user
  validates :user, presence: true
  validates :first_name, presence: true, on: :update
  validates :last_name, presence: true, on: :update
end

我想编写一些rspec测试来测试first_name和last_name的验证,但我看不到如何仅在模型测试中更新时运行profile.should_not be_valid。喜欢的东西;

it "should be invalid without a first name on update" do
  profile = FactoryGirl.build :profile
  profile.first_name = nil
  profile_should_not be_valid
end

没有区分更新或创建操作,我在rspec文档中看不到任何关于此的内容。当然,测试是一件相当普遍的事情。

1 个答案:

答案 0 :(得分:3)

rspec中的

be_valid只是在模型上调用valid?

profile = FactoryGirl.build :profile

这为Profile构建了一个新的模型实例,但是没有将它提交给数据库。您可以使用此profile进行创建测试。将:first_name设置为nil应该通过调用profile.should be_valid

profile = FactoryGirl.create :profile

这将构建并将Profile的模型实例插入到数据库中。您可以使用此profile进行更新测试。将:first_name设置为nil应调用profile.should be_valid 失败