发现Invalid Record factory girl中的错误

时间:2014-04-29 20:24:23

标签: ruby-on-rails testing activerecord rspec factory-bot

我有这样的用户工厂:

FactoryGirl.define do
  factory :user do
    email "email@x.com"
    password "123456789"
  end
end

我正在尝试为用户创建规范:

describe User do
  it "should create a user with password" do
    user = FactoryGirl.create(:user, password: "secret")
    user.password.should == "secret"
  end   
end

当我运行测试时,我收到此消息:

  1) User should create a user with password
     Failure/Error: user = FactoryGirl.create(:user, password: "secret")
     ActiveRecord::RecordInvalid:
       is invalid
     # ./spec/models/user_spec.rb:3:in `block (2 levels) in <top (required)>'
     # -e:1:in `<main>'

问题是:如何发现模型中哪些字段无效?换句话说,如何在模型中打印错误消息?

2 个答案:

答案 0 :(得分:6)

您可以随时暂时将测试更改为:

user = FactoryGirl.build(:user, password: "secret")

然后检查user.valid?user.errors

答案 1 :(得分:0)

有时,build方法会为您提供相同的ActiveRecord::RecordInvalid: Record invalid。在这种情况下,您可能希望查找工厂创建的任何关联记录,可能验证问题来自那些。