Rspec验证失败:电子邮件不能为空,电子邮件请以正确的格式输入电子邮件

时间:2019-07-24 15:58:19

标签: ruby-on-rails unit-testing rspec

我正在尝试编写一个用于测试电子邮件验证的测试,但我不确定为什么会导致错误, 这是测试:

我的spec.rb

-- :name get-status
-- :doc fetch the status of a specific message
-- :command :query
-- :return :many
/* :require [clojure.string :as s] */
SELECT
    *
FROM
    message_status
/*~
(let [params (filter (comp some? val) params)]
  (when (not (empty? params))
    (str "WHERE "
      (s/join " AND "
              (for [[field _] params]
                (str (name field) " = " field))))))
~*/

模型

 describe 'POST Coupon /scooties_coupons/:coupon_id' do
    subject { post "/api/scooties_coupons/#{scooties_coupon.id}", headers: headers }

    context 'without API_KEY' do
      let(:api_key) { nil }

      it 'returns HTTP unauthorized' do
        subject
        expect(response).to have_http_status(401)
      end
    end

这是错误:

class ScootiesCoupon < ApplicationRecord


  after_update :send_activecamp_email_scootiescoupon

  validates :email, presence: true, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i, message: "please enter emails in correct format" }

end

这是控制器

  2) /scooties_coupon POST Coupon /scooties_coupons/:coupon_id without API_KEY returns HTTP unauthorized
     Failure/Error: let(:scooties_coupon) { create :scooties_coupon }

     ActiveRecord::RecordInvalid:
       Validation failed: Email can't be blank, Email please enter emails in the correct format

  def create

    @scooties_coupon = ScootiesCoupon.new(scooties_coupon_params)

    if @scooties_coupon.save
      redirect_to  scooties_coupons_new_path, notice: 'We will get in touch if your email is valid!'
    else
      render :new
    end
  end

不完全确定工厂做什么

1 个答案:

答案 0 :(得分:0)

由于电子邮件中存在状态的验证设置为true,因此数据库中保留的任何对象都必须包含有效的电子邮件,而该电子邮件不在您的工厂中:

FactoryBot.define do
  factory :scooties_coupon do
    coupon { "43MDA" }
    redeemed { false }
    email { "email@host.com" }

    trait :redeemed do
      redeemed { true }
    end
  end
end

您可以添加一个愚蠢且“静态”的电子邮件来尝试,也可以使用stympy/faker gem这样的其他邮件。