ruby 如何使用Rails和RSpec正确测试类方法?

ar5n3qh5  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(121)

使用Spec测试类方法
你好,
我刚刚开始使用Rails和RSpec测试。我需要为一个现有的系统开发一个特性,所以我决定开始使用行为驱动开发。我通过安装以下gem来设置RSpec for Rails:

group :test do
  gem 'cucumber-rails', :require => false
  gem 'database_cleaner'
  gem 'rspec-rails'
  gem "capybara", ">= 2.15"
  gem "selenium-webdriver"
  gem "webdrivers"
  gem "httparty", "~> 0.18.1"
end

字符串
在Specs文件夹中,我创建了services文件夹,然后创建了测试文件:santander_payslip_controller.rb.

require 'rails_helper'
require 'payslip'

describe Payslip, type: :service do

    describe ".authenticate" do
      santander = Payslip::Santander.new "xxxx", "xxxx", "xxxx"
      context "given the client_id and client_secret" do
      
        it "fails without the digital certificate" do
          expect(santander.authenticate()).not_to eql('201')
        end
      
      end
    
    end

end


我需要测试一个类方法,该方法将验证Santander API是否能够对类authenticate方法执行身份验证。包含需要测试的方法的类位于包含HTTPartygem的方法下。

module Payslip  

  class Santander
    include HTTParty
    
    def initialize(client_id, client_secret, account_id)
      @client_id = client_id
      @client_secret = client_secret
      @account_id = account_id
      @base_uri = Rails.configuration.santander_base_uri
    end

    def authenticate()
      url = @base_uri + '/token'
      params = {
        "client_id" => @client_id,
        "client_secret" => @client_secret,
        "grant_type" => "client_credentials"
      }
      payload = {body: params}
      response = post(url, payload).symbolize_key
      response.code
    end

end


每当我运行rspec命令执行测试时,我都会看到ruby抱怨无法识别post方法(HTTParty)。

F

Failures:

  1) Payslip.authenticate given the client_id and client_secret fails without the digital certificate
     Failure/Error: response = post(url, payload).symbolize_key

     NoMethodError:
       undefined method `post' for #<Payslip::Santander:0x0000000108e51330>
      ./app/services/payslip.rb:23:in `authenticate'
      ./spec/services/santander_payslip_controller_spec.rb:11:in `block (4 levels) in <top (required)>'

Finished in 0.01818 seconds (files took 3.95 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/services/santander_payslip_controller_spec.rb:10 # Payslip.authenticate given the client_id and client_secret fails without the digital certificate


你能帮我指出我在Ruby、RSpec或Rails配置中可能做错了什么吗?
作为参考,我使用的是Rails6.1、Ruby2.6.3和RSpec3.12
我希望我能理解如何正确地配置RSpec,并使它理解我的类使用的HTTParty方法。

rseugnpd

rseugnpd1#

您只需要在Payslip::Santander#authenticate方法中将此post(url, payload)更改为self.class.post(url,payload)
这与RSpec测试无关,它只是HTTParty的工作方式。当你调用include HTTParty时,它又调用extend ClassMethods作为Module#included钩子的一部分。#post方法在HTTParty::ClassMethods模块中定义。

  • HTTParty::包含
  • HTTParty::ClassMethods#post

相关问题