Rails 和 Rspec 单元测试静态方法

Rails and Rspec Unit Testing Static Methods

我的一个模型中有一个非常简单的静态方法:

def self.default
    self.find(1)
end

我正在尝试为其编写一个简单的 Rspec 单元测试,它不会对数据库进行任何调用。我如何编写一个测试来生成一些示例实例以供测试 return?请随意完成此操作:

describe ".default" do
    context "when testing the default static method" do
        it "should return the instance where id = 1" do

        end
    end
end

模型文件如下:

  class Station < ApplicationRecord
  acts_as_paranoid
  acts_as_list
  nilify_blanks

  belongs_to :color
  has_many :jobs
  has_many :station_stops
  has_many :logs, -> { where(applicable_class: :Station) }, foreign_key: :applicable_id
  has_many :chattels, -> { where(applicable_class: :Station) }, foreign_key: :applicable_id

  delegate :name, :hex, to: :color, prefix: true

  def name
    "#{full_display} Station"
  end

  def small_display
    display_short || code.try(:titleize)
  end

  def full_display
    display_long || small_display
  end

  def average_time
    Time.at(station_stops.closed.average(:time_lapsed)).utc.strftime("%-M:%S")
  end

  def self.default
    # referencing migrate/create_stations.rb default for jobs
    self.find(1)
  end

  def self.first
    self.where(code: Constant.get('station_code_to_enter_lab')).first
  end
end

spec文件如下:

require "rails_helper"
describe Station do

  subject { described_class.new  }

  describe "#name" do
    context "when testing the name method" do
      it "should return the capitalized code with spaces followed by 'Station'" do
        newStation = Station.new(code: 'back_to_school')
        result = newStation.name
        expect(result).to eq 'Back To School Station'
      end
    end
  end

  describe "#small_display" do
    context "when testing the small_display method" do
      it "should return the capitalized code with spaces" do
        newStation = Station.new(code: 'back_to_school')
        result = newStation.small_display
        expect(result).to eq 'Back To School'
      end
    end
  end

  describe "#full_display" do
    context "when testing the full_display method" do
      it "should return the capitalized code with spaces" do
        newStation = Station.new(code: 'back_to_school')
        result = newStation.full_display
        expect(result).to eq 'Back To School'
      end
    end
  end

  describe ".default" do
    context "" do
      it "" do

      end
    end
  end

end

您可以使用 stubbing 到达那里

describe ".default" do
    context "when testing the default static method" do
        let(:dummy_station) { Station.new(id: 1) }
        before { allow(Station).to receive(:default).and_return(dummy_station)

        it "should return the instance where id = 1" do
          expect(Station.default.id).to eq 1
        end
    end
end