代码之家  ›  专栏  ›  技术社区  ›  Billy Logan

在RSpec中获取未定义的方法错误

  •  -1
  • Billy Logan  · 技术社区  · 9 年前

    我正在使用RSpec和FactoryGirl测试我的模型,我一直在使用“highest_priority”方法,因为某种原因,RSpec无法看到这种方法。

    下面是方法本身:

    模型/任务.rb

    class Task < ActiveRecord::Base
    
    #some stuff
    
     def self.highest_priority
        p = Task.order(:priority).last.try(:priority)
        p ? p + 1 : 1
      end
    end
    

    当我跑步时 任务规范.rb

    require 'spec_helper'
    
    describe Task do
    
    it "returns highest priority" do
      last_task = FactoryGirl.build(:task, priority: "5")
      last_task.highest_priority
      expect(last_task(:priority)).to eq("6")
     end
    end
    

    我收到以下错误: enter image description here

    当我像这样在控制器中调用此方法时

     def create
        @task = current_user.tasks.build(task_params)
        @task.highest_priority
        @task.complete = false
    
    
        respond_to do |format|
          if @task.save
            format.js
          else
            format.js
          end
        end
      end
    

    方法看起来像

      def highest_priority
        self.maximum(:priority).to_i + 1
      end
    

    我得到了

    enter image description here

    2 回复  |  直到 9 年前
        1
  •  1
  •   Mohammad AbuShady ALoK VeRMa    9 年前

    首先,最好使用ActiveRecord maximum 您将避免实例初始化,而是直接从查询中获取一个数字

    Task.maximum(:priority)
    

    这可以放在这样的类方法中

    def self.maximum_priority
      Task.maximum(:priority) || 0 # fall back to zero if no maximum exists
    end
    

    然后,对于更新方法的后半部分,我将为此创建一个实例方法,并使用类方法

    def set_maximum_priority
      self.priority = self.class.maximum_priority + 1
    
      self
    end
    

    请注意,我在结尾处返回了self,以获得可链接性

    那么你的行动就会变成这样

    def create
        @task = current_user.tasks.build(task_params).set_maximum_priority
        @task.complete = false
        ...
    end
    
        2
  •  1
  •   Arup Rakshit    9 年前

    您需要将该方法创建为 Task 模型如下所示:

    class Task < ActiveRecord::Base
    
      #some stuff
    
      def highest_priority
        p = Task.order(:priority).last.try(:priority)
        p ? p + 1 : 1
      end
    end