我做错了什么 - 语法错误意外' \ n',期待=>

时间:2016-11-17 20:57:53

标签: ruby-on-rails ruby

这是我的Ruby代码(我在Hartl的Ruby on Rails指南中跟随)这是User_test.rb

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

错误如下,我无法弄清楚如何修复它 - 任何更有经验的人都知道我做错了什么?

 1) Error:
UserTest#test_email_validation_should_reject_invalid_addresses:
SyntaxError: /home/ubuntu/workspace/app/models/user.rb:4: syntax error,       unexpected '\n', expecting =>

这是User.rb代码

class User < ActiveRecord::Base
  has_many :microposts

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name, presence: true, length: { maximum: 50},
  validates :email, presence: true, length: { maximum: 255},
  format: { with: VALID_EMAIL_REGEX }, uniqueness: true, case_sensitive: false              
end

1 个答案:

答案 0 :(得分:1)

validates :name, presence: true, length: { maximum: 50},

你需要删除,,Ruby认为你继续定义你的Hash。

unexpected '\n', expecting => 基本上意味着Ruby不期望一个新的行,而是使用键后跟=>和值的哈希定义。

PS:还有一个原因我不喜欢缩写的Ruby Hash表示法。在代码中找不到=>,这使得理解错误消息变得更加困难。