【问题标题】:How to mock out calls to open-uri如何模拟对 open-uri 的调用
【发布时间】:2014-01-26 03:17:45
【问题描述】:

我有一个使用“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 'open' 方法,使其 (1) 不会尝试上网并且 (2) 不会破坏我的测试?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3 rspec tdd


【解决方案1】:

为什么不重构:

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

然后你可以存根和测试:

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

【讨论】:

  • 漂亮。很好的解决方案。我必须使用described_class.any_instance.stub(:open_and_read).with(picture).and_return('picture_as_url') 才能使其正常工作,但现在所有测试都通过了。谢谢!
  • 可能还想使用更新的 rspec 语法:expect(subject.from).to eq([ sender_address ])
猜你喜欢
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多