【问题标题】:Rspec testing complex code with undefined variablesRspec 使用未定义变量测试复杂代码
【发布时间】:2011-08-31 12:27:53
【问题描述】:

在 rspec 测试方面只需要一点帮助...对它很陌生,不太知道如何测试这段代码

# Get a list of tasks recently used by the user
    recent_task_ids = Effort.all( :select => "project_task_id",
                                  :conditions => { :user_id => @user_id },
                                  :group => "project_task_id",
                                  :order => "MAX( week_commencing )" )


    # For each of the task ids, get the actual project task records
    @recent_tasks = []
    recent_task_ids.each do |effort|
      if ProjectTask.find_by_id( effort.project_task_id ) != nil
        @recent_tasks.push( ProjectTask.find( effort.project_task_id ) )
      end
    end

不确定您是否应该以这种方式测试未定义的变量,但任何帮助都会很棒

【问题讨论】:

    标签: ruby-on-rails-3 testing rspec


    【解决方案1】:

    您可以删除 Effort.all 方法。

    it "tests with nil values" do
      Effort.stub(:all).and_return(nil)
    end
    

    来源:http://rspec.info/documentation/mocks/stubs.htmlhttp://rspec.info/documentation/mocks/

    【讨论】:

    • 感谢两个问题。 1,在例子theres! .和 2 你把 nil 放在哪里,我说 id 把我正在寻找的属性放在哪里是对的吗?所以 Effort.stub!(:all).and_return(:select => "project_task_id", :conditions => { :user_id => @user_id }, :group => "project_task_id", :order => "MAX( week_commencing ) ")
    • 存根!在 RSpec2 中已弃用。 2) 您正在测试 Effort.all 何时返回 nil 的属性,因此将返回值保留为 nil。如果您不为其他测试存根,那么它们应该像现在一样工作。
    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多