Marian
Marian

Reputation: 4079

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

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: "[email protected]") }
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 "[email protected]":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.

Upvotes: 0

Views: 752

Answers (3)

Tom7
Tom7

Reputation: 11

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.

Upvotes: 1

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

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.

Upvotes: 0

Billy Chan
Billy Chan

Reputation: 24815

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

Upvotes: 2

Related Questions