Michael Hartl的教程第6章:由于模型上的Syntax_error而导致测试失败

时间:2015-04-09 13:55:33

标签: ruby-on-rails testing

6.27列表中的测试是针对pass的,但是我不断收到13个错误,这些错误都引用了相同的语法错误:

Syntax Error:       SyntaxError: /home/action/workspace/app/app/models/user.rb:6: syntax error, unexpected ':', expecting keyword_end

这是似乎导致错误的模型,但我没有看到任何错误:

  1  class User < ActiveRecord::Base
  2  validates :name,  presence: true, length: { maximum: 50 }
  3  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  4  validates :email, presence: true, length: { maximum: 255 },
  5                         format: { with: VALID_EMAIL_REGEX }
  6                         uniqueness:  {case_sensitive: false} 
  7  end 

最初它说的是错误是第6行,在唯一性和开放括号之间出现了意外的关键字“:”,但在经过一些修补之后,这似乎已经停止了。

关于本章的关于SO的一些问题似乎源于测试本身的缩进,所以为了完整性,我将把它们包含在这里:

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 "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 accept valid addresses" do
    valid_addresses = %w[user@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn]
    valid_addresses.each do |valid_address|
      @user.email = valid_address
      assert @user.valid?, "#{valid_address.inspect} should be valid"
     end
  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
    duplicate_user.email = @user.email.upcase
      @user.save
      assert_not duplicate_user.valid?
    end
  end

1 个答案:

答案 0 :(得分:1)

您在第5行末尾缺少,

请参阅Listing 6.24

上的代码
class User < ActiveRecord::Base
  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: true
end