[英]How to create test data in rspec
Hi i am working on rails app with ruby-2.5.0 and Rails 5. I have to test my forgot_password controller there is a method which validates if the email id is presnt in the database or not. 嗨,我正在使用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
I want to test my api. 我想测试我的api。 i have written unit testing as follows:-
我已经编写了如下单元测试:
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
Now i want to create test data with 'let' like 现在我想用'let'创建测试数据
let(:user) { instance_double('user') }
let(:save_result) { true }
How can i create user with let please help me. 我该如何创建用户,请帮助我。 Thanks in advance.
提前致谢。
I'd look into using FactoryBot aka FactoryGirl as it makes writing that stuff out easier. 我会考虑使用FactoryBot aka FactoryGirl,因为它可以使编写这些内容变得更加容易。 But for your case this should be what your looking for:
但是对于您的情况,这应该是您想要的:
let(:user) { User.create!(email: 'xyz@gmail.com', password: 'pass', password_confirmation: 'pass') }
If you had FactoryBot, you could simplify that with: 如果您拥有FactoryBot,则可以使用以下方法简化该操作:
let(:user) { create(:user) }
Or possibly for better performance, if you don't actually need a record created but simply built: 或者可能是为了获得更好的性能,如果您实际上不需要创建而是仅创建一条记录:
let(:user) { build_stubbed(:user) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.