(1)当需要重复使用的测试情况,可以用shared_examples("describe") do end提出来,在需要使用的地方可以使用it_behaves_like "describe"复用,代码写在controller_spec.rb文件中
(2)可以将大量重复使用的代码,单独提出来,放在spec/support/下放在Module中,并在spec/spec_helper.rb文件中的RSpec.configure块中,加入config.include Moudle, 或者直接在spec/support下或子文件夹下写个rb文件,spec_helper.rb会自动require,如下代码:
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
(3)可以使用自定义匹配器简化代码,例如登陆功能:
spec/support/matchers/require_login.rb
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
使用:
expect(response).to require_login