ruby-on-rails – 使用RSpec在控制器中测试实例变量
发布时间:2020-12-17 04:24:00 所属栏目:百科 来源:网络整理
导读:给定一个这样的控制器,它创建了几个供视图使用的实例变量,你通常会测试每个变量是否正确设置?看起来你想要,但它似乎有点可能有点棘手.什么是正确的方法? class StaffsController ApplicationController def index set_index_vars @all_staff = Staff.find_
给定一个这样的控制器,它创建了几个供视图使用的实例变量,你通常会测试每个变量是否正确设置?看起来你想要,但它似乎有点可能有点棘手.什么是正确的方法?
class StaffsController < ApplicationController def index set_index_vars @all_staff = Staff.find_staff_for_business_all_inclusive(current_business_id) respond_to do |format| format.html { render :action => "index",:locals => { :all_staff => @all_staff,:all_services => @all_services,:new_vacation => @new_vacation } } end end def set_index_vars @days_of_week = days_of_week @first_day_of_week = DefaultsConfig.first_day_of_week @all_services = Service.services_for_business(current_business_id) @new_vacation = StaffVacation.new @has_hit_staff_limit = current_user_plan.has_hit_staff_limit? end end 该代码也发布于https://gist.github.com/1018190 解决方法
如果你要写一个控制器规范,那么是的,一定要测试实例变量的分配.大多数’棘手’可能来自对其他模型/库的依赖,因此存在这些方法调用:
# air code Staff.stub(:find_staff_for_business_all_inclusive) {array_of_staff} controller.stub(:days_of_week) {['Monday','Tuesday',....etc...]} DefaultsConfig.stub(:first_day_of_week) {"Monday"} Service.stub(:services_for_business).with(some_value_for_the_current_business_id). and_return(some_relevant_value) StaffVacation.stub(:new) {something_meaningful} controller.stub_chain(:current_user_plan,:has_hit_staff_limit?) {false} get :index assigns(:days_of_week).should == ['Monday',....etc...] # ...etc... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |