gpt4 book ai didi

ruby-on-rails - 如何模拟对 open-uri 的调用

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

我有一个使用“open-uri”的邮件程序。

require 'open-uri'
class NotificationMailer < ActionMailer::Base

def welcome(picasa_picture)
picture = picasa_picture.content.src
filename = picture.split('/').last
attachments.inline[filename] = open(picture).read
mail(
to: 'foo@exmample.com',
from: 'bar@example.com',
subject: 'hi',
)
end
end

但是当我尝试测试类中的任何内容时,出现此错误:

 SocketError:
getaddrinfo: nodename nor servname provided, or not known

我找到了这个 SO 帖子:How to rspec mock open-uri并认为这会有所帮助。我试了一下:

let(:pic_content) { double(:pic_content, src: 'http://www.picasa/asdf/asdf.jpeg') }
let(:picture) { double(:picture, content: pic_content) }
let(:open_uri_mock) { double(:uri_mock, read: true) }

subject { described_class.welcome(picture) }

it 'renders email address of sender' do
subject.stub(:open).and_return(open_uri_mock)
subject.from.should == [ sender_address ]
end

我还尝试了“should_receive”而不是“stub”,但没有用。

如何抑制 open-uri 的“打开”方法,使其 (1) 不会尝试连接到 Internet 并且 (2) 不会破坏我的测试?

最佳答案

为什么不重构:

require 'open-uri'
class NotificationMailer < ActionMailer::Base

def welcome(picasa_picture)
picture = picasa_picture.content.src
filename = picture.split('/').last
attachments.inline[filename] = open_and_read(picture)
mail(
to: 'foo@exmample.com',
from: 'bar@example.com',
subject: 'hi',
)
end

def open_and_read(picture)
open(picture).read
end

end

然后你可以 stub 和测试:

subject { NotificationMailer }

before do
subject.stub(:open_and_read).and_return(:whatever_double_you_want)
subject.welcome(picture)
end

it 'renders email address of sender' do
subject.from.should == [ sender_address ]
end

关于ruby-on-rails - 如何模拟对 open-uri 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21359225/

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