【问题标题】:Practical example of mock and stubs in railsrails 中 mock 和 stub 的实际示例
【发布时间】:2014-08-11 19:45:36
【问题描述】:

有足够多的questions 与此主题相关,但没有提供practial 示例引用差异。

根据Fowler 的文章模拟不是存根,存根是独立于外部调用的假方法,而模拟是对调用有预编程反应的假对象。

Stub 不会让您的测试失败,但 Mocks 可以。

模拟更具体且与对象相关:如果某些参数是 通过,则对象返回一定的结果。一个人的行为 对象被模仿或“嘲笑”。

存根更通用且与方法相关:通常是存根方法 对所有参数返回相同的结果。一个人的行为 方法被冻结、罐装或“存根”。

我们来看一个简单的test 案例。我们必须找到一个 Book 提供了 id 并与用户相关。

  it "can find an Book that this user belongs to" do 
    project = Book.find( id: '22', email: user@test.com )      
    expect(project) to eq(some_data);  
  end

在上述情况下...什么是存根,什么是模拟?如果我的示例无效,谁能告诉我example 的 Mock and 存根。

【问题讨论】:

  • 你能链接提到的文章吗?
  • 是的,所以我认为这篇文章是关于 Java 的,使用的命名约定是指一些 Java 特定的约定,与 Ruby 和 Rspec 没有任何关系:)

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


【解决方案1】:

让我们举两个例子:

let(:email) { 'email' }

# object created from scratch
let(:mocked_book) { instance_double Book, email: email } 
it 'check mock' do
  expect(mocked_book.email).to eq email
end

# 
let(:book) { Book.new }
it 'check stub' do
  allow(book).to receive(:email) { email }
  expect(book.email).to eq email
end

您的示例无关紧要:您不会测试活动记录,但您可能需要 stub 它返回 mock

假设你需要测试一本书的接收方法,比如:

def destroy
  @book = Book.find(params[:id])
  if @book.destroyable?
    @book.destroy
  else
    flash[:error] = "errr"
  end
  redirect_to books_path
end

您可以使用以下代码进行测试:

it 'is not destroyed if not destroyable' do
  mocked_book = double 'book', destroyable?: false
  allow(Book).to receive(:find).and_return mocked_book
  expect(mocked_book).to_not receive :destroy
  # here goes the code to trigger the controller action
end

it 'is destroyed if destroyable' do
  mocked_book = double 'book', destroyable?: true
  allow(Book).to receive(:find).and_return mocked_book
  expect(mocked_book).to receive :destroy
  # here goes the code to trigger the controller action
end

您可以在这里查看优缺点:

  • 缺点:mock 必须确切知道预期的方法是什么

  • 优点:使用 mock,您无需真正创建对象并对其进行设置以使其适合某些条件

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 2020-10-21
    • 2011-11-12
    • 2010-10-02
    • 1970-01-01
    • 2014-06-21
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多