(1)當須要重複使用的測試狀況,能夠用shared_examples("describe") do end提出來,在須要使用的地方可使用it_behaves_like "describe"複用,代碼寫在controller_spec.rb文件中ruby
(2)能夠將大量重複使用的代碼,單獨提出來,放在spec/support/下放在Module中,並在spec/spec_helper.rb文件中的RSpec.configure塊中,加入config.include Moudle, 或者直接在spec/support下或子文件夾下寫個rb文件,spec_helper.rb會自動require,以下代碼:app
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }測試
(3)可使用自定義匹配器簡化代碼,例如登錄功能:ui
spec/support/matchers/require_login.rburl
RSpec::Matchers.define :require_login do |attribute| match do |actual| expect(attribute).to \ redirect_to Rails.application.routes.url_helpers.login_path end failure_message_for_should do |actual| "expected to require login to access the method" end failure_message_for _should_not do |actual| "expected not to require login ro access the method" end description do "redirect to the login form" end end
使用:code
expect(response).to require_login