【问题标题】:How to debug RSpec tests?如何调试 RSpec 测试?
【发布时间】:2014-07-10 16:12:18
【问题描述】:

我在我的 rails 应用程序中使用 devise 进行授权,但在开发的单元测试部分中遇到了一些问题。

  it "is invalid with a duplicate email address" do
    User.create(
      name: 'Joe', surname: 'Tester', email: 'tester@example.com', password: 'password123', password_confirmation: 'password123'
      )
    user = User.new(
      name: 'Jane', surname: 'Tester', email: 'tester@example.com', password: 'password123', password_confirmation: 'password123'
      )
    pp user.errors.inspect
    expect(user).to have(1).errors_on(:email)

  end

但为此我得到expected 1 errors on :email, got 2

您能否建议我如何弄清楚另一个错误是什么?我试过pp user.errors.inspect,但不是很有用。

谢谢。

编辑 pp user.errors.inspect 产生以下结果:

"#<ActiveModel::Errors:0x000000058016c8 @base=#<User id: nil, name: \"Jane\", surname: \"Tester\", about: nil, level: nil, city: nil, created_at: nil, updated_at: nil, email: \"tester@example.com\", encrypted_password: \"$2a$04$TfDBOXXDhUDVuJhPmxbu9eRZsTQ.Om8X5k5YkeDg51e...\", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>, @messages={}>"
F

Failures:

  1) User is invalid with a duplicate email address
     Failure/Error: expect(user).to have(1).errors_on(:email)
       expected 1 errors on :email, got 2

【问题讨论】:

  • 为什么没有用?它产生了什么?
  • @UriAgassi 更新了我的问题。
  • 如果你只是想打印出错误,你可以试试 user.errors.full_messages ?
  • 在打印错误之前,您需要在使用对象上调用valid?save(即创建错误时)

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


【解决方案1】:

这个测试似乎很难维护(如果你将另一个属性设置为强制,你将不得不重构这个测试)。

您可能希望定义您的测试以真正尊重其描述:

it "is invalid without a password" do
  User.create(name: 'Joe', surname: 'Tester', email: 'tester@example.com', password: 'password123', password_confirmation: 'password123')
  user = User.create(email: 'tester@example.com')
  user.should_not be_valid
  user.errors.messages[:email].present?.should be true
end

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多