首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rspec不查找类方法

Rspec不查找类方法
EN

Stack Overflow用户
提问于 2017-07-21 15:23:12
回答 2查看 1.6K关注 0票数 0

我正在为我的后端工作编写一些测试,而rspec没有找到我的方法,我遇到了一个奇怪的问题。

我编写了一个简单的类&测试来说明这个问题:

app/interactors/tmp_test.rb:

代码语言:javascript
复制
class TmpTest
  def call
    a = 10
    b = 5
    b.substract_two
    return a + b
  end

  def substract_two
    c = self - 2
    return c
  end
end

spec/interactors/tmp_test.rb:

代码语言:javascript
复制
require 'rails_helper'

describe TmpTest do
  context 'when doing the substraction' do
    it 'return the correct number' do
      expect(described_class.call).to eq(13)
    end
  end
end

产出:

代码语言:javascript
复制
TmpTest
  when doing the substraction
    return the correct number (FAILED - 1)

Failures:

  1) TmpTest when doing the substraction return the correct number
     Failure/Error: expect(described_class.call).to eq(13)

     NoMethodError:
       undefined method `call' for TmpTest:Class
     # ./spec/interactors/tmp_test.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.00177 seconds (files took 1.93 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/interactors/tmp_test.rb:5 # TmpTest when doing the substraction return the correct number
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-21 15:28:07

它不是一个类方法,而是一个实例方法。您的测试应该如下所示:

代码语言:javascript
复制
describe TmpTest do
  subject(:instance) { described_class.new }

  context 'when doing the subtraction' do
    it 'returns the correct number' do
      expect(instance.call).to eq(13)
    end
  end
end
票数 2
EN

Stack Overflow用户

发布于 2017-07-21 15:38:01

这真是一团糟。更正后的版本,并附有评论:

代码语言:javascript
复制
class TmpTest
  def call
    a = 10
    b = 5
    # b.substract_two # why do you call method of this class on b?!
    a + subtract_two(b)
  end

  def substract_two(from)
    from - 2
  end
end

另外:不要在方法的最后一行中使用return

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45241328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档