【问题标题】:Testing XmlBuilder with Rspec使用 Rspec 测试 XmlBuilder
【发布时间】:2015-05-07 07:54:58
【问题描述】:

我发布了一个关于使用 XmlBuilder 呈现 XML 的问题 (Rails XML builder not rendering)。该特定问题已解决,但我在测试此控制器操作时遇到了另一个问题。

问题似乎出在 Rspec 上,因为用 Minitest 编写的相同测试可以正常工作,并且使用 cURL 也可以。

在调试时,Rspec 从不尝试呈现 xml 构建器模板。它只是跳过模板并呈现带有空白正文的 http 状态 200。

这里是控制器、xml builder、测试和测试结果:

控制器/bars_controller.rb

require 'builder'

class BarsController < ApplicationController

  def show
    @bar = Bar.find(params[:id])
    render template: 'bars/show.xml.builder', formats: [:xml]
  end

 end

/views/bars/show.xml.builder

xml.instruct!
xml.bar do
  xml.foo(@bar.foo)
  xml.bar(@bar.bar)
end

/test/controllers/bars_controller_test.rb

 require 'test_helper'

 class BarsControllerTest < ActionController::TestCase
  setup do
    @bar = Bar.create(foo: 'bar', bar: 'foo')
  end

  test "should show bar" do
    get :show, id: @bar
    assert_response :success
    assert_match "<bar>", response.body
  end
 end

/spec/controllers/bars_controller_spec.rb

 require_relative '../rails_helper'

 describe BarsController do

  describe 'a POST to :show' do
    before do
      @bar = Bar.create(foo: 'bar', bar: 'foo')
      post :show, id: @bar
    end

    it 'should show bar' do
      expect(response).to be_success
      expect(response.body).to include("<bar>")
    end
  end
 end

测试结果

> rake test
Run options: --seed 50688

# Running:
.
Finished in 0.096901s, 10.3198 runs/s, 30.9593 assertions/s.
1 runs, 3 assertions, 0 failures, 0 errors, 0 skips

> rspec spec/controllers/bars_controller_spec.rb 
F

Failures:

  1) BarsController a POST to :show responds with xml bar
     Failure/Error: expect(response.body).to include("<bar>")
       expected "" to include "<bar>"
     # ./spec/controllers/bars_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

Finished in 0.01726 seconds (files took 1.53 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/bars_controller_spec.rb:11 # BarsController a POST to :show responds with xml bar

【问题讨论】:

    标签: ruby-on-rails xml rspec xml-builder


    【解决方案1】:

    RSpec 控制器测试默认不渲染视图。为了呈现视图,将render_views 添加到描述块:

    describe 'a POST to :show' do
      render_views
    
      before do
        @bar = Bar.create(foo: 'bar', bar: 'foo')
        post :show, id: @bar
      end
    
      it 'should show bar' do
        expect(response).to be_success
        expect(response.body).to include("<bar>")
      end
    end
    

    【讨论】:

    • 谢谢!我整天都在为这个问题头疼。你认为我应该把它转移到更合适的测试类型吗?
    • 如果您要对 XML 输出进行大量测试,我可能会将这些测试移至视图规范中。功能规格似乎有点过头了。
    猜你喜欢
    • 2014-08-16
    • 2017-06-28
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多