我在应用程序控制器中有一个简单的方法:
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
...
总是有另一套规格失败(我想是订单问题),但我不知道是什么破坏了东西?第二个规范与第一个规范没有任何不同,那么它会打破什么呢?
如果必须这样做,可以使用Rspec的匿名控制器,如所述
...
controller do
def index
project = create(:project)
render json: filename_for_export(project, 'Audit', 'pdf')
end
end
it 'appends a format extension if given' do
get :index
expect(JSON.parse(response.body)).to eq 'Project test customer - Project test name (Audit, Access for all, 2015-06-15).pdf'
end
然而,我强烈建议您简单地将此方法提取到一个普通的旧ruby对象中,并将其作为单元测试进行隔离测试。您为"常规"控制器方法编写的请求规范应该涵盖集成。