我遵循Rails教程建模用戶章節:http://www.railstutorial.org/book/modeling_users#cha-modeling_users。Rails教程驗證問題
我user.rb樣子:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
has_secure_password
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
end
和我的用戶模型規格的樣子:
describe User, :type => :model do
before do
@user = User.new(name: "Example User", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
subject { @user }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:authenticate) }
it { should be_valid }
... (other methods are here)
describe "when password is not present" do
before do
@user = User.new(name: "Example User", email: "[email protected]",
password: "foobar", password_confirmation: "foobar")
end
it { should_not be_valid }
end
describe "return value of authenticate method" do
before { @user.save }
let(:found_user) { User.find_by(email: @user.email) }
describe "with valid password" do
it { should eq found_user.authenticate(@user.password) }
end
describe "with invalid password" do
let(:user_for_invalid_password) { found_user.authenticate("invalid") }
it { should_not eq user_for_invalid_password }
specify { expect(user_for_invalid_password).to be_false }
end
end
這一點我敢肯定是完全的複製Rails的教程代碼是什麼,但我得到以下失敗的測試錯誤:
rspec ./spec/models/user_spec.rb:83 # User when password is not present should not be valid
rspec ./spec/models/user_spec.rb:108 # User return value of authenticate method with invalid password should be false
你能在問題補充完整的錯誤跟蹤解決第二個。 –
@infinity它也考慮到了,請檢查測試數據庫中是否還有用戶的電子郵件地址爲「[email protected]」。從命令行:1. rails console test 2. user = User.find_by_email(「[email protected]」)3.如果上一個命令找到用戶,則需要刪除它:user.destroy或者,如果用戶存在於數據庫中,您可能需要考慮每次使用新的電子郵件地址(電子郵件地址中的某些隨機部分)在測試中創建用戶。 – jyrkim