首页 > 其他 > 详细

RSpec控制器测试重构

时间:2015-04-13 19:07:50      阅读:221      评论:0      收藏:0      [点我收藏+]

(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


RSpec控制器测试重构

原文:http://my.oschina.net/u/1413049/blog/400668

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!