ruby-on-rails 我在理解如何使用webmock测试从api获取消息时遇到了困难

ffx8fchx  于 2022-12-01  发布在  Ruby
关注(0)|答案(1)|浏览(140)

我目前正在尝试为这个方法编写一个测试:

#fetch message from api

def message_instance
    project_id = ENV['SIGNALWIRE_PROJECT_KEY']
    project_tkn = ENV['SIGNALWIRE_TOKEN']
    host_url = ENV['SIGNALWIRE_HOST']
@client = Signalwire::REST::Client.new project_id, project_tkn, signalwire_space_url: host_url
    message = @client.messages(sid).fetch
end

并且我正在使用FactoryBot来模拟接收到的消息@message = build:message,status::已收到
但是我不知道如何测试方法的每一行。希望有人能分解我如何正确地为这个请求存根?
编辑:我到目前为止,我已经尝试了这个:

describe 'message_instance' do
      it 'returns message instance' do
        
        allow(ENV).to receive(:[]).with('SIGNALWIRE_PROJECT_KEY').and_return('AC123')
        @message = build :message, status: 'received', sid: '123456789'
       
       
        @message.message_instance.should eq @client
        
      end
    end

返回以下错误:

"BUNDLER_ORIG_RUBYLIB"=>"BUNDLER_ENVIRONMENT_PRESERVER_INTENTIONALLY_NIL", "BUNDLER_ORIG_RUBYOPT"=>"BUNDLER_ENVIRONMENT_PRESERVER_INTENTIONALLY_NIL", "BUNDLE_GEMFILE"=>"/vagrant/oyetext-backend/Gemfile", "BUNDLE_BIN_PATH"=>"/usr/share/rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/bundler-2.1.4/libexec/bundle", "BUNDLER_VERSION"=>"2.1.4", "RUBYOPT"=>"-r/usr/share/rvm/rubies/ruby-2.7.2/lib/ruby/2.7.0/bundler/setup", "RUBYLIB"=>"", "RAILS_ENV"=>"test", "SIGNALWIRE_PROJECT_KEY"=>"test", "SIGNALWIRE_TOKEN"=>"test", "SIGNALWIRE_NUMBER"=>"+19999999999"} received :[] with unexpected arguments
         expected: ("SIGNALWIRE_PROJECT_KEY")
              got: ("SIGNALWIRE_TOKEN")
        Please stub a default value first if message might be received with other args as well.
2w2cym1i

2w2cym1i1#

我真的不认为stubbing ENV是一个好主意,因为你可以看到它被用于比你的代码逻辑更多的东西,比如bundler或ruby本身。
我不调用allow(ENV).to...,而是尝试使用以下代码:

ENV['SIGNALWIRE_PROJECT_KEY'] = 'AC123'

相关问题