gpt4 book ai didi

Ruby:const_set 外 block ?

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:37 30 4
gpt4 key购买 nike

我要mock a class with Ruby .

如何编写处理样板代码的方法?

以下代码:

module Mailgun

end

module Acani
def self.mock_mailgun(mock)
temp = Mailgun
const_set(:Mailgun, mock)
p Mailgun
yield
ensure
const_set(:Mailgun, temp)
end
end

Acani.mock_mailgun('mock') { p Mailgun }

打印:

"mock"
Mailgun

这是怎么回事?为什么 Mailgun 是 block 内的原始值?这与 Ruby 绑定(bind)有关吗?

ruby 版本:2.1.1p76

最佳答案

尝试将 Object. 放在每个 const_set 之前。

问题中的代码被简化了。以下是相关代码:

test/test_helper.rb

require 'minitest/autorun'

module Acani
def self.const_mock(const, mock)
temp = const_get(const)
const_set_silent(const, mock)
yield
ensure
const_set_silent(const, temp)
end

private

def self.const_set_silent(const, value)
temp = $VERBOSE
$VERBOSE = nil
Object.const_set(const, value)
ensure
$VERBOSE = temp
end
end

test/web_test.rb

require 'test_helper'
require 'rack/test'
require_relative '../web'

class AppTest < MiniTest::Test
include Rack::Test::Methods

def app
Sinatra::Application
end

def test_password_reset
post '/users', {email: 'user1@gmail.com', password: 'password1'}

mailgun_mock = MiniTest::Mock.new
mailgun_mock.expect(:send, 200, [Hash])

Acani.const_mock(:Mailgun, mailgun_mock) do
post '/password_resets', {email: 'user1@gmail.com'}
end

mailgun_mock.verify
assert_equal 201, last_response.status
end
end

关于Ruby:const_set 外 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23071671/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com