【问题标题】:How to do testing in rails using rspec with factory girl?如何使用带有工厂女孩的 rspec 在 Rails 中进行测试?
【发布时间】:2018-03-24 04:56:48
【问题描述】:

您好,我正在使用 ruby​​ 2.5.0 和 rails 5 开发 rails 应用程序。我编写了一个 api 来检查用户是否存在提供的用户名和令牌。

check_token_controller.rb
class CheckTokenController < ApplicationController

    def create
        begin
            user = User.where(email: check_params[:username], token: check_params[:token]).first
            if user.blank?
                render json: {},
                 status: 401
            else
                render json: {},
                 status: 200
            end
        rescue => e
            render json: {},
                 status: 500
        end
    end

    private

  def check_params
    permitted = %i[username token]
    params.require(:data)
          .require(:attributes)
          .permit(permitted)
          .transform_keys(&:underscore)
  end
end

现在我想在我的 spec.rb 文件中测试这个 api。

*spec/controllers/check_token_controller_spec.rb
require 'rails_helper'

describe CheckTokenController do

    let(:user) { instance_double('user') }
  let(:save_result) { true }
  let(:params) do
    { data: { attributes: { fullname: 'michael febrianto',email: 'saddam@gmail.com', token: 'rWCyRUgfLODuc8B4DvA_8w',password: 'password' } } }
  end

  before do
    allow(User).to receive(:new).and_return(user)
    allow(user).to receive(:save).and_return(save_result)
  end

  let(:params) do
    { data: { attributes: { username: 'saddam@gmail.com', token: 'rWCyRUgfLODuc8B4DvA_8w' } } }
  end

  describe 'POST create' do
    subject { post :create, params: params }

    context 'when success' do
      it { is_expected.to have_http_status(200) }
    end

    context 'when failed' do
      it { is_expected.to have_http_status(401) }
    end
  end
end

我现在是第一次使用 rspec,每当我运行这个测试时,它不会创建任何我用调试器检查过的测试数据。请帮助我如何创建测试数据,然后我可以测试我的 api。提前致谢。

【问题讨论】:

  • 有什么问题?哪个测试失败了?

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


【解决方案1】:

请翻阅书籍:

使用 RSpec 进行日常 Rails 测试

RSpec 书籍:行为驱动开发

他们可能会帮助你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多