未定义的方法“保存"使测试在测试结束之前失败 [英] undefined method `save' making test fail before testing to the end

查看:17
本文介绍了未定义的方法“保存"使测试在测试结束之前失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 ruby​​.railstutorial.org.我遇到了一些麻烦,但我解决了它们.但是,现在我在谷歌上搜索了很长时间,检查了代码,我什至知道测试失败的原因,但不知道如何使其通过.

I am following ruby.railstutorial.org. I have had some troubles, but I solved them. Now, however, I am googling for quite some time, checked the code, I even have an idea why test fails, but have no clue as to how to make it pass.

那么,问题来了.我有一个用户模型:

So, here's the problem. I have a User model:

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 中的测试是:

The problem is related to the case insensitive uniqueness check. The test in Rspec is:

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)>'

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

So the model even fails to save. And I have no idea what to do. However, if we comment out the following line from the test:

user_with_same_email = @user.email.upcase

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

and remove the { case_sensitive: false } part from the model code, test passes. What I want the test to do is to actually save the user_with_same_email variable and then report that it is not valid. Any help/links/suggestions are very appreciated.

推荐答案

这行确实有问题

user_with_same_email = @user.email.upcase

user_with_same_email 是一个对象,您需要设置电子邮件地址而不是对象本身.

user_with_same_email is an object, you need to set the email attr instead of the object itself.

user_with_same_email.email = @user.email.upcase

这篇关于未定义的方法“保存"使测试在测试结束之前失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆