未定义的方法`save’使测试在测试结束前失败

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

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

class User < ActiveRecord::Base attr_accessible :email, :name validates :name, presence: true, length: {maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[az\d\-.]+\.[az]+\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 ' 

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

 user_with_same_email = @user.email.upcase 

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

这条线确实有问题

 user_with_same_email = @user.email.upcase 

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

 user_with_same_email.email = @user.email.upcase 

它说user_with_same_email是一个字符串,没有save方法。

猜测,我想你需要使用该电子邮件创建一个用户对象,这样你就可以测试你的代码找到它并抛出validation。

在我自己的指令中,我被这个错误简单地贬低了。 一般来说,如果遇到任何类似的问题,我建议你去教程的帮助部分。 如果没有涉及该问题,那么您可以查看链接到github的Official Sample Code链接。 该问题的代码在该存储库中是正确的。 干杯。