【问题标题】:How to mock JSONP call in rspec request spec with capybara?如何使用水豚模拟 rspec 请求规范中的 JSONP 调用?
【发布时间】:2012-06-24 12:00:05
【问题描述】:

我正在将我的 rails 应用程序与 Recurly.js 集成。

在我从服务器端应用程序发出 recurly 请求之前,因此我能够存根与优秀的 VCR gem (https://github.com/myronmarston/vcr) 的所有集成,但 Recurly.js 使用 JSONP 从 javascript 代码直接向服务发出请求。

问题是:如何在集成测试中模拟这些jsonp调用?

目前我正在使用 rspec + capybara + phantomjs 驱动程序 (https://github.com/jonleighton/poltergeist)

【问题讨论】:

    标签: ruby-on-rails rspec jsonp integration-testing capybara


    【解决方案1】:

    我想出的唯一方法是即时 javascript 修补。至于 Poltergeist gem 有一个方法可以在测试浏览器中执行 javascript,您可以应用以下补丁将 Recurly.js 转换为测试模式:

    # The original 'save' function performs JSONP request to Recurly.
    # A token is borrowed during the real API interaction.
    page.driver.execute_script("""
      Recurly.Subscription.save = function (options) {
        Recurly.postResult('/subscription', { token: 'afc58c4895354255a422cc0405a045b0' }, options);
      }
    """)
    

    只需制作一个水豚宏,给它起一个花哨的名称,例如“stub_recurly_js”,并在每次提交 Recurly.js 表单之前调用。

    如果您想更深入地挖掘,这里也是原始帖子的链接:http://pieoneers.tumblr.com/post/32406386853/test-recurlyjs-in-ruby-using-rspec-capybara-phantomjs

    【讨论】:

    【解决方案2】:

    使用puffing-billy。它会在您的测试浏览器和外部世界之间注入一个代理服务器,并允许您伪造特定 URL 的响应。

    例子:

    describe 'my recurly jsonp spec' do
    
      before do
        # call proxy.stub to setup a fake response
        proxy.stub 'https://api.recurly.com/v2/foo', :jsonp => { :bar => 'baz' }
      end
    
      it 'does something with recurly' do
        ....
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      相关资源
      最近更新 更多