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

标签 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

我找到了这个 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/

相关文章:

ruby-on-rails - PostgreSQL 版本 13 psql : error: could not connect to server: could not connect to server: No such file or directory

javascript - 检查 cookie 是否存在于 javascript 中

ruby-on-rails - 如何接受逗号分隔列表来为模型构建标签?

ruby - 在类中动态创建静态变量

mysql - rake 中止!无法加载此类文件 -- El Capitan 上的 mysql2/mysql2

ruby-on-rails-3 - link_to对象数组,但具有新路径

ruby-on-rails - 将正则表达式的值存储到 Ruby 中的变量

ruby-on-rails - PG::ConnectionBad: 无法连接到服务器:连接被拒绝

Ruby:一次从一个字符串和两个数组值构建哈希

ruby-on-rails - Rails 中确定两个(或更多)给定 URL(作为字符串或哈希选项)是否相等的最佳方法是什么?