使用Rspec存根昂贵的方法

时间:2018-08-30 17:33:22

标签: ruby-on-rails ruby rspec

在以下情况下,我只想将哈希传递给存根测试双。我不想测试双重本身。但是我需要在测试中模仿它。实际方法如下所示:

# user.rb
def do_work
  assignments = fetch_assignments
  if assignments.any?
    assignments.each do |assignment|
      if assignment.valid?
        client.approve_assignment({assignment_id: assignment.assignment_id})
      else
        client.reject_assignment({assignment_id: assignment.assignment_id})
      end
    end 

    mark_assignments_as_complete    
  end
end

现在,我可以轻松测试除客户端以外的所有功能。客户端是一个真正昂贵的(每次查询要花钱)API查询,我不想每次运行测试都运行。所以我使用测试双打和存根:

describe "#do_work" do
  context "when two assignments are valid" do
    before :context do
      @user = User.create!({name: "Bob"})
      [{assignment_id: "1", valid: false}, {assignment_id: 2, valid: false}, {assignment_id: "3", valid: true}].each do |assignment|
        @user.assignments.create!(assignment)
      end
      @client = ExpensiveAPI.new
      @user.client = @client
    end
  end

  describe "#do_work" do
    it "accepts valid assignments" do
      user.valid_assignments.each do |assignment|
        allow(@client).to receive(:accept_assignment, {assignment_id: assignment.assignment_id}).and_return(true)
      end

      expect(@user.do_work).to have 2_completed_assignments
    end

    it "rejects invalid assignments" do
      user.valid_assignments.each do |assignment|
        allow(@client).to receive(:accept_assignment, {assignment_id: assignment.assignment_id}).and_return(true)
      end

      expect(@user.do_work).to have 1_incomplete_assignment
    end
  end
end

当我尝试将参数传递给存根方法时,出现此错误:

ArgumentError: wrong number of arguments (2 for 1)

1 个答案:

答案 0 :(得分:0)

我认为这是一个语法问题。对带有参数的方法进行存根的格式(按照https://relishapp.com/rspec/rspec-mocks/v/2-99/docs/method-stubs)是:

allow(obj).to接收(:message).with('an arguments'){...}

但是您将期望的参数作为第二个参数传递给receive(...),这就是为什么它抱怨只需要一个参数。

将您的规范更改为此:

describe "#do_work" do
  context "when two assignments are valid" do
    before :context do
      @user = User.create!({name: "Bob"})
      [{assignment_id: "1", valid: false}, {assignment_id: 2, valid: false}, {assignment_id: "3", valid: true}].each do |assignment|
        @user.assignments.create!(assignment)
      end
      @client = ExpensiveAPI.new
      @user.client = @client
    end
  end

  describe "#do_work" do
    it "accepts valid assignments" do
      user.valid_assignments.each do |assignment|
        allow(@client).to receive(:accept_assignment).with({assignment_id: assignment.assignment_id}).and_return(true)
      end

      expect(@user.do_work).to have 2_completed_assignments
    end

    it "rejects invalid assignments" do
      user.valid_assignments.each do |assignment|
        allow(@client).to receive(:accept_assignment).with({assignment_id: assignment.assignment_id}).and_return(true)
      end

      expect(@user.do_work).to have 1_incomplete_assignment
    end
  end
end