加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 对如何使用mock和stubs感到困惑

发布时间:2020-12-17 02:34:34 所属栏目:百科 来源:网络整理
导读:我有一个班级和规格. class Store def activate(product_klass,product_id) product = product_klass.find(product_id) if product.inactive? product.update_attribute :active,true end endenddescribe Store do it "should activate an inactive product"
我有一个班级和规格.

class Store
  def activate(product_klass,product_id)
    product = product_klass.find(product_id)
    if product.inactive?
      product.update_attribute :active,true
    end
  end
end

describe Store do
  it "should activate an inactive product" do
    product = mock
    product.stub(:inactive?).and_return(true)    
    store = Store.new
    store.activate(22) # 
    product.should be_active
  end
end

运行规范失败.我明白了:

Mock received unexpected message :find_by_id with (1)

为了满足这一点,我在line store.activate(product,22)之前添加了product.should_receive(:find_by_id).with(1).and_return(product). (这似乎是错误的事情,因为我不希望我的测试过多地了解我正在测试的方法的内部)

再次运行规范,我得到失败,其中以下行返回false而不是预期的true:

product.should be_active

因此,它返回false,因为product.update_attribute:active,true并没有真正将active设置为true:它只是被mock所吸收.

我有很多问题.如何进行rspec’cing?我应该如何测试这个呢?我是否正确使用了模拟和存根?

任何帮助深表感谢.

解决方法

我认为激活逻辑根本不属于Store.如果它在Product中声明,那么对我来说测试看起来会更自然:

class Product < ActiveRecord::Base
  def activate
    if inactive?
      update_attribute :active,true
    end
  end
end

describe Product do
  it "should activate an inactive product" do
    product = Product.new
    product.activate 
    product.should be_active
  end
end

从那里你可以像这样重写你的Store方法:

class Store
  def activate(product_klass,product_id)
    product = product_klass.find(product_id)
    product.activate
  end
end

describe Store do
  it "should activate an inactive product" do
    product = mock
    product.should_receive(:activate)
    product_klass = mock
    product_klass.should_receive(:find).with(22).and_return(product)
    store = Store.new
    store.activate(product_klass,22)
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读