ruby-on-rails - 使用 RSpec 测试 Controller 中的实例变量

标签 ruby-on-rails rspec

给定一个像这样的 Controller ,它创建了几个供 View 使用的实例变量,您通常会测试每个变量是否正确设置?看起来你会想要,但它似乎也有点棘手。什么是正确的做法?

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

最佳答案

如果您要编写 Controller 规范,那么是的,一定要测试实例变量是否已分配。大部分“棘手”可能来自对其他模型/库的依赖,因此排除这些方法调用:

# 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','Tuesday',....etc...]
# ...etc...

关于ruby-on-rails - 使用 RSpec 测试 Controller 中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6301791/

相关文章:

ruby-on-rails - rspec 测试有问题,未定义的方法 'post'

ruby 测试 : Testing for the Absence of a Method

ruby-on-rails - 使用 Rspec GET 发送格式

sql - Rails select() 和 count() 似乎不太好用

ruby-on-rails - Controller 类中的 session 和 params 之间的区别

ruby-on-rails - 如何只解析 CSV 文件的第一行?

ruby - 如何测试带有参数的创建 Action 的康康舞能力?

css - 如何防止重复元素显示?

javascript - 如何显示和链接对象的某个属性

ruby-on-rails - 无需通过路由即可测试 Controller