RSpec控制器测试重构

(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


转载于:https://my.oschina.net/u/1413049/blog/400668

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值