ruby-on-rails - 你如何在 Rails 中使用 Rspec 测试你的配置/初始化脚本?

标签 ruby-on-rails rspec config rspec-rails initializer

所以我在网上搜索解决方案,但似乎很少有关于测试在 Rails 中创建的初始化程序的信息。

目前,我已经在我的 config/initializers/retrieve_users.rb 文件中编写了一个相当大的 API call-n-store。它发出 API 请求,解析 JSON,然后将数据存储为用户。相当可观,我还没有想出最干净的方法来测试它。由于我需要在运行任何函数之前检索用户,因此我不相信我可以将此脚本移至其他任何地方(尽管欢迎其他建议)。我对此有几个问题:

  • 我是否必须将它包装在一个函数/类中来测试我的代码?
  • 我会把我的规范文件放在哪里?
  • 我将如何格式化它 RSpec 风格?

  • 谢谢!

    最佳答案

    我只是试了一下,并通过了 rspec 测试,我将进一步重构我的代码,最后它会更短,但这里是我所做的快照,使用 this link as a guide:

    它的要点是:在你的初始化文件中用你想要的函数创建一个类,然后对类中的函数编写测试。

    配置/初始化程序/stripe_event.rb

    StripeEvent.configure do |events|
      events.subscribe 'charge.dispute.created' do |event|
        StripeEventsResponder.charge_dispute_created(event)
      end
    end
    
    class StripeEventsResponder
      def self.charge_dispute_created(event)
        StripeMailer.admin_dispute_created(event.data.object).deliver
      end
    end
    

    规范/配置/初始化程序/stripe_events_spec.rb
    require 'spec_helper'
    
    describe StripeEventsResponder do
      before { StripeMock.start }
      after { StripeMock.stop }
      after { ActionMailer::Base.deliveries.clear }
    
      describe '#charge_dispute_created' do
        it "sends one email" do
          event = StripeMock.mock_webhook_event('charge.dispute.created')
          StripeEventsResponder.charge_dispute_created(event)
          expect(ActionMailer::Base.deliveries.count).to eq(1)
        end
    
        it "sends the email to the admin" do
          event = StripeMock.mock_webhook_event('charge.dispute.created')
          StripeEventsResponder.charge_dispute_created(event)
          expect(ActionMailer::Base.deliveries.last.to).to eq(["admin@example.com"])
        end
      end
    end
    

    关于ruby-on-rails - 你如何在 Rails 中使用 Rspec 测试你的配置/初始化脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25147236/

    相关文章:

    ruby-on-rails - 如何创建独特的延迟工作

    mysql - 'rake db:create' 或 'rake about' 上的 RoR 4 错误

    sql - 向 ActiveRecord 查询添加计算列

    ruby - 如何创建沙盒 RSpec 环境?

    ruby-on-rails - 测试速度 : ActiveRecord use_transactional_fixtures vs. DatabaseCleaner.strategy = :transaction

    ruby-on-rails - Rspec raise_error 不适用于自定义错误

    javascript - Ruby on Rails : accessing form elements with javascript

    mysql - json 或 mysql 进行配置哪个更快?

    git - 不要使用 GIT 覆盖 Azure 上的配置文件

    linux - 如何在 Bash 中取消设置以特定前缀开头的所有变量?