如何模拟open-uri的调用

时间:2014-01-26 03:17:45

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

我有一个使用' 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

我发现了这个帖子: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;注意&#39;而不是&#39; stub&#39;,但它没有帮助。

我如何压制开放式的开放式网站?方法,以便(1)不尝试上网和(2)不打破我的测试?

1 个答案:

答案 0 :(得分: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