无法找到没有ID的用户Hartl rails tutorial

时间:2017-12-18 10:20:00

标签: ruby-on-rails ruby activerecord

我在rails中的项目有问题 我正在从railstutorial.org学习,我在列出〜6.18时遇到问题 这是回购 https://github.com/Mroczeks/first_project 这是错误:

rails test
Running via Spring preloader in process 10776
Started with run options --seed 33787

 FAIL["test_schould_be_valid", UserTest, 0.6801217989996076]
 test_schould_be_valid#UserTest (0.68s)
        Expected false to be truthy.
        test/models/user_test.rb:9:in `block in <class:UserTest>'

ERROR["test_email_addresses_should_be_saved_as_lower-case", UserTest, 0.6879979369996363]
 test_email_addresses_should_be_saved_as_lower-case#UserTest (0.69s)
ActiveRecord::RecordNotFound:         ActiveRecord::RecordNotFound: Couldn't find User without an ID
            test/models/user_test.rb:45:in `block in <class:UserTest>'

 FAIL["test_email_validation_should_accept_valid_addresses", UserTest, 0.7056386839994957]
 test_email_validation_should_accept_valid_addresses#UserTest (0.71s)
        "user@example.com" should be valid
        test/models/user_test.rb:32:in `block (2 levels) in <class:UserTest>'
        test/models/user_test.rb:30:in `each'
        test/models/user_test.rb:30:in `block in <class:UserTest>'

  18/18: [=================================] 100% Time: 00:00:00, Time: 00:00:00

Finished in 0.78367s
18 tests, 29 assertions, 2 failures, 1 errors, 0 skips

2 个答案:

答案 0 :(得分:3)

在user_test.rb文件中保存@user对象时,此错误的原因似乎是验证失败。尝试使用以下代码替换此测试,您将在运行此测试时看到失败的验证:

test "email addresses should be saved as lower-case" do
  mixed_case_email = "Foo@ExAMPle.CoM"
  @user.email = mixed_case_email

  # Calling `save!` here will raise an exception if failed to save @user.
  @user.save!
  assert_equal mixed_case_email.downcase, @user.reload.email
end

修复您的setup方法以相应地满足所有验证,然后重试。

答案 1 :(得分:3)

User模型中,您的defined password length validation最低为6,但在测试设置中,created the userpassword: 'pies'。因此,您将获得所有错误和失败:

FAIL["test_schould_be_valid", UserTest, 0.6801217989996076]
test_schould_be_valid#UserTest (0.68s)
    Expected false to be truthy.
    test/models/user_test.rb:9:in `block in <class:UserTest>'

要解决所有错误,您需要使用UserTest#setup中的有效数据初始化用户。在这种情况下,您只需提供最小长度为6的密码。