【问题标题】:Chapter 6 of RailsTutorial.org by Michael Hartl Rspec Blank Email checkRailsTutorial.org 第 6 章作者 Michael Hartl Rspec 空白电子邮件检查
【发布时间】:2013-10-22 23:11:52
【问题描述】:

在 Michael Hartl 编写的 Ruby on Rails 教程的 chapter 6.x 中,我无法让 Rspec 通过 email is not present 检查。

根据我有限的知识:

  • User_spec 使用 before do 之后的代码创建测试用户。
  • 然后根据user.rb 中的属性检查该用户以使 确保:presence 有效。
  • 如果有效,则检查返回 true 或 false。
  • 在下一个代码中,在 { @user.email = " " } 之前将电子邮件设置为 空的
  • 然后说it { should_not be_valid }

但是,它失败了 User when email is not present 错误。

/spec/models/User_spec.rb

require 'spec_helper'

describe User do

  before do
    @user = User.new(name: "Example User", email: "user@example.com")
  end

  subject { @user }

  it { should respond_to(:name) }
  it { should respond_to(:email) }

  it { should be_valid }

  describe "when email is not present" do
    before { @user.email = " " }
    it { should_not be_valid }
  end
end

spec/models/user.rb

class User < ActiveRecord::Base
  validates :name,  presence: true
  validates :email, presence: true
end

失败:

1) 电子邮件不存在时的用户 失败/错误:它 { should_not be_valid } 预期 # 无效 # ./spec/models/user_spec.rb:18:in `block (3 levels) in '

Finished in 0.03278 seconds
4 examples, 1 failure

Failed examples:

rspec ./spec/models/user_spec.rb:18 # User when email is not present

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-on-rails-4


    【解决方案1】:

    您正在验证电子邮件是否存在,这意味着如果值为 nil 或空字符串,它将失败。

    在描述不应出现电子邮件的情况的 rspec 块中,您将电子邮件地址定义为由单个空格组成的字符串。您实际上想通过删除空格来使其成为空白字符串:

    before { @user.email = "" }
    

    现在验证将失败。

    【讨论】:

    • 空字符串与空字符串不同,对吗?那么 email = ""} 是否只检查一个空白框而不是如果电子邮件为空呢?我有任何意义吗?哈哈
    • 好吧,我会用空白和空来表示同一件事,因为空格仍然是一个字符。您示例中的字符串是" " - 请注意空格。根据rails,这是一个非空字符串,也不是空白。
    • 澄清:在rails中,"".blank? == "".empty? == true,但" ".blank? == true; " ".empty? == false!!换句话说,包含空格的字符串为空,但非空
    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多