【问题标题】:undefined method `save' making test fail before testing to the end未定义的方法“保存”使测试在测试结束之前失败
【发布时间】:2013-05-13 16:07:54
【问题描述】:

我正在关注 ruby​​.railstutorial.org。我遇到了一些麻烦,但我解决了它们。然而,现在我在谷歌上搜索了很长一段时间,检查了代码,我什至知道为什么测试失败了,但不知道如何让它通过。

所以,这就是问题所在。我有一个用户模型:

class User < ActiveRecord::Base
  attr_accessible :email, :name

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

问题与不区分大小写的唯一性检查有关。 Rspec 中的测试是:

before { @user = User.new(name: "Example User", email: "user@example.com") }
subject { @user }

describe "when email address is already in use" do
    before do
        user_with_same_email = @user.dup
        user_with_same_email = @user.email.upcase
        user_with_same_email.save
    end

    it { should_not be_valid }
end

测试错误信息如下:

Failures:
1) User when email address is already in use 
    Failure/Error: user_with_same_email.save
    NoMethodError:
    undefined method `save' for "USER@EXAMPLE.COM":String
# ./spec/models/user_spec.rb:53:in `block (3 levels) in <top (required)>'

所以模型甚至无法保存。我不知道该怎么做。但是,如果我们从测试中注释掉以下行:

user_with_same_email = @user.email.upcase

并从模型代码中删除 { case_sensitive: false } 部分,测试通过。 我希望测试做的是实际保存 user_with_same_email 变量,然后报告它无效。 非常感谢任何帮助/链接/建议。

【问题讨论】:

    标签: ruby-on-rails rspec railstutorial.org


    【解决方案1】:

    这条线确实有问题

    user_with_same_email = @user.email.upcase
    

    user_with_same_email是一个对象,需要设置email attr而不是对象本身。

    user_with_same_email.email = @user.email.upcase
    

    【讨论】:

    • 谢谢!这个错误太蹩脚了,我什至看不到它。现在会更加关注。
    【解决方案2】:

    我自己在说明中的这个错误中一度偏离了方向。一般来说,如果遇到任何类似的问题,我建议您前往the tutorial 的帮助部分。如果那里没有涵盖该问题,那么您可以查看指向Official Sample Code 的链接,该链接指向github。此问题的代码在该存储库上是正确的。干杯。

    【讨论】:

      【解决方案3】:

      这是说 user_with_same_email 是一个字符串,没有保存方法。

      猜想,我会说您需要使用该电子邮件创建一个用户对象,以便您可以测试您的代码是否找到它并引发验证。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-27
        • 2019-12-29
        • 1970-01-01
        • 1970-01-01
        • 2013-02-27
        • 1970-01-01
        • 2018-05-05
        相关资源
        最近更新 更多