如何在应用程序控制器中测试方法?我的方法使其他测试随机崩溃

时间:2016-05-09 12:34:37

标签: ruby-on-rails rspec

我在应用程序控制器中有一个简单的方法:

class ApplicationController < ActionController::Base
  def filename_for_export(project, type, format = nil)
    buffer = "#{project.customer} - #{project.name} (#{type}, #{t 'org.name'}, #{Date.today.to_s :db})"
    buffer += ".#{format}" if format
    buffer
  end
end

我有以下测试:

describe ApplicationController do
  describe '#filename_for_export' do
    before { @controller = ApplicationController.new }

    it 'returns a good human readable filename' do
      project = create(:project)
      result = @controller.instance_eval{ filename_for_export(project, 'Audit') }
      expect(result).to eq 'Project test customer - Project test name (Audit, Access for all, 2015-06-15)'
    end
  end
end

一切正常。然后我又添了一个测试:

it 'appends a format extension if given' do
  project = create(:project)
  result = @controller.instance_eval{ filename_for_export(project, 'Audit', 'pdf') }
  expect(result).to eq 'Project test customer - Project test name (Audit, Access for all, 2015-06-15).pdf'
end

也工作正常。但有趣的是,第二次测试似乎打破了一些让许多其他规格随机失败的东西:

...
rspec ./spec/features/file_upload_spec.rb:18 # File upload displays a preview of an uploaded file
rspec ./spec/features/file_upload_spec.rb:4 # File upload allows to upload a file
rspec ./spec/features/file_upload_spec.rb:27 # File upload displays a preview of an uploaded file (from the temporary cache) after a re-display of the form
rspec ./spec/features/file_upload_spec.rb:60 # File upload allows to remove a file
rspec ./spec/features/markdown_spec.rb:4 # Markdown uses Pandoc as converter for inline markdown
rspec ./spec/features/users/destroy_spec.rb:22 # Deleting user signed in as admin grants permission to delete other user
rspec ./spec/features/success_criteria/show_spec.rb:6 # Showing success criterion displays a success criterion
rspec ./spec/features/boilerplate_originals/edit_spec.rb:11 # Editing boilerplate grants permission to edit a boilerplate
...

总是另一组规格失败(我猜这是一些订单问题),但我不知道什么可能破坏事情?第二个规范与第一个规范没有任何不同,那么它会破坏什么呢?

1 个答案:

答案 0 :(得分:0)

如果你必须这样做,你可以使用Rspec的匿名控制器,如here所述

invariant.js:38 Uncaught (in promise) Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `Header`.(…)

但是,我强烈建议您只是将此方法提取到一个普通的旧ruby对象中,然后单独测试它作为单元测试。该请求规定了您的常规&#39;控制器方法应该涵盖整合。