アプリケーションコントローラーでメソッドをテストする方法は?私のアプローチでは、他のテストがランダムにクラッシュします

ジョシュア・ムハイム

アプリケーションコントローラーに簡単な方法があります。

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

また、正常に動作しています。しかし興味深いことに、この2番目のテストは、他の多くの仕様をランダムに失敗させる何かを壊しているようです。

...
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
...

それは常に失敗する別の仕様のセットです(私はそれが何らかの順序の問題だと思います)が、何が物事を壊す可能性があるのか​​分かりませんか?この2番目の仕様は1番目の仕様と何も変わらないので、何が壊れるのでしょうか。

Jan Bussieck

これを行う必要がある場合は、ここで説明するように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

ただし、このメソッドを単純な古いルビーオブジェクトに抽出し、単体テストとして単独でテストすることを強くお勧めします。リクエストは、「通常の」コントローラーメソッドの書き込みが統合をカバーするように指定します。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ