【发布时间】:2018-03-26 17:44:29
【问题描述】:
您好,我正在使用 ruby-2.5.0 和 Rails 5 开发 rails 应用程序。我必须测试我的 forgot_password 控制器,有一种方法可以验证数据库中是否存在电子邮件 ID。
forgot_password_controller.rb
# frozen_string_literal: true
class ForgotPasswordController < ApplicationController
def create
user = User.find_by_email(forgot_password_params[:email])
unless user.blank?
render json: {}, status: 200
else
render json: {}, status: 404
end
rescue StandardError
render json: {}, status: 500
end
private
def forgot_password_params
permitted = %i[email]
params.require(:data)
.require(:attributes)
.permit(permitted)
.transform_keys(&:underscore)
end
end
我想测试我的 api。我编写的单元测试如下:-
forgot_password_controller_spec.rb
# frozen_string_literal: true
require 'rails_helper'
describe ForgotPasswordController do
before do
User.create!(email: 'xyz@gmail.com',
password: 'pass',
password_confirmation: 'pass')
end
describe 'POST create' do
subject { post :create, params: params }
context 'when email is found' do
let(:params) do
{ data: { attributes: { email: 'xyz@gmail.com' } } }
end
it { is_expected.to have_http_status(200) }
end
context 'when email is not found' do
let(:params) do
{ data: { attributes: { email: 'xyz2@gmail.com' } } }
end
it { is_expected.to have_http_status(404) }
end
context 'when wrong params passed' do
let(:params) do
{ data: '' }
end
it { is_expected.to have_http_status(500) }
end
end
end
现在我想用 'let' 创建测试数据 喜欢
let(:user) { instance_double('user') }
let(:save_result) { true }
如何创建用户让请帮助我。提前致谢。
【问题讨论】:
标签: ruby-on-rails unit-testing rspec