Railstutotal(Michael Hartl):代码6.25出错

时间:2017-04-16 18:07:05

标签: ruby-on-rails

所以我到目前为止遵循了Rails教程,直到我进入清单6.25之前一切正常。教程说“轨道测试”应该是绿色的,但我变红了。

错误

失败: UserTest#test_email_addresses_should_be_unique [location] 预期是零或假

我99%肯定我完全按照这本书,不知道出了什么问题。

这是user.rb

class User < ApplicationRecord
    attr_accessor :name, :email

    validates :name, presence: true, length: { maximum: 50 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    validates :email, presence: true, length: {maximum: 255}, 
        format: {with: VALID_EMAIL_REGEX}, 
        uniqueness: true
end

和user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  def setup
    @user = User.new(name: "Example User", email: "user@example.com")
  end

  test "should be valid" do
    assert @user.valid?
  end

  test "name should be present" do
    @user.name = "     "
    assert_not @user.valid?
  end

  test "email should be present" do
    @user.email = "     "
    assert_not @user.valid?
  end

  test "name should not be too long" do
    @user.name = "a" * 51
    assert_not @user.valid?
  end

  test "email should not be too long" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

  test "email validation should reject invalid addresses" do
    invalid_addresses = %w[user@example,com user_at_foo.org user.name@example.
                       foo@bar_baz.com foo@bar+baz.com]
    invalid_addresses.each do |invalid_address|
      @user.email = invalid_address
      assert_not @user.valid?, "#{invalid_address.inspect} should be invalid"
    end
  end

  test "email addresses should be unique" do
    duplicate_user = @user.dup
    @user.save
    assert_not duplicate_user.valid?
  end

end

2 个答案:

答案 0 :(得分:0)

删除此行,它会混淆ActiveRecord

_ = Alamofire.request(Path.mainPageCollections.url, method: .get, parameters: nil, encoding: URLEncoding.default).responseObject(completionHandler: callback)

答案 1 :(得分:0)

我不知道你所拥有的书的哪个版本,但这就是现在书中的方式:

class User < ApplicationRecord
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
end

没有attr_accessor:name,:email

您还应该将唯一性更改为:

uniqueness: { case_sensitive: false }

否则,只需使用大写字母或下注即可使用相同的电子邮件。我认为这应该可行。 以下是新书的链接,如果你没有使用它,哪个更好,因为你会遇到更少的错误:

https://www.railstutorial.org/book/modeling_users#sec-uniqueness_validation