undefined method `save' making test fail before testing to the end

谁说胖子不能爱 提交于 2019-12-02 15:46:24

问题


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

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

The test error message is as follows:

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

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.


回答1:


This line does have problem

user_with_same_email = @user.email.upcase

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



回答2:


It's saying user_with_same_email is a string and doesn't have a save method.

Guessing, I'd say you need to create a user object with that email, so you can test that your code finds it and throws the validation.




回答3:


I was briefly sidetracked by this error in the instruction myself. In general if one encounters any similar issues I recommend going to the help section of the tutorial. If the issue isn't covered there then you could check out the link to the Official Sample Code that links to github. The code for this issue is correct on that repository. Cheers.



来源:https://stackoverflow.com/questions/16526507/undefined-method-save-making-test-fail-before-testing-to-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!