RSpec控制器测试重构

(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
相关文章
相关标签/搜索