使用rspec显示模型验证错误

时间:2013-12-01 14:41:53

标签: ruby-on-rails rspec

我在模型规范中有一个上下文和7个期望:

describe User do

    context "with all valid attributes" do
        before { @user = FactoryGirl.build(:user_with_all_valid) }

        subject { @user }

        it { should be_valid }

        its(:first_name) { should == "Jimmy" }
        its(:last_name) { should == "Thehat" }
        its(:profile_name) { should == "Jimbohatboy893" }
        its(:email) { should == "awesomedog@hotmail.co.uk" }
        its(:password) { should == "thisisasupersecretpassword12234234" }
        its(:password_confirmation) { should == "thisisasupersecretpassword12234234" }
    end
end

运行这个我得到一些奇怪的结果:

14:35:13 - INFO - Running: spec

F......

Failures:

  1) User with all valid attributes should be valid
     Failure/Error: it { should be_valid }
       expected valid? to return true, got false
     # ./spec/model/user_spec.rb:29:in `block (3 levels) in <top (required)>'

Finished in 0.5358 seconds
7 examples, 1 failure

好的,验证期望it { should be_valid }失败了。公平,但为什么所有其他的期望,测试其first_name,last_name等传递?如果验证没有通过,那么这些属性肯定不会写入数据库,因此这些期望不应该通过?怀疑我在这里有错误的想法,他们无法写入数据库。我希望能够测试一下,为了安心。

我真正的问题是调试。如何将验证错误消息打印到控制台? expected valid? to return true, got false仅描述症状。我想first_name length too long或类似。

2 个答案:

答案 0 :(得分:3)

很抱歉告诉你,但你的测试很糟糕:他们的意思是什么?测试工厂的参数?

增值是什么?

检查模型在db(there are dedicated matchers but this is debatable)或respond_to方法中是否包含字段会更有意义。

当您使用对象实例时,即使它们没有被保留,字段也会在内存中设置,它解释了测试通过的原因。

要获取错误,您应该添加调试语句,或者只是在控制台中检查工厂为什么不构建有效对象。

it 'debugging...' do
  puts subject.valid?
  puts subject.errors
  # or debugger
  # or binding.pry
  subject.should be_valid
end

答案 1 :(得分:0)

只是一个小小的东西,但基于apneadiving的答案,这给出了关于属性及其错误的良好输出:

it 'debugging...' do
    subject.errors.each do |a, e|   
       puts a
       puts e
       puts "----"
    end
end
相关问题