我应该在测试时在Factory girl或spec文件中对模型进行存根处理吗? [英] Should I stub the model in Factory girl or in the spec file while testing?

查看:79
本文介绍了我应该在测试时在Factory girl或spec文件中对模型进行存根处理吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的几乎每个规格文件都最终写出如下内容:

Almost every spec file I come accross I end up writing stuff like:

  before :each do
    @cimg = Factory.build :cimg_valid
    @cimg.stub(:validate_img).and_return true
    @cimg.stub(:validate_img_url).and_return true
    @cimg.stub(:save_images).and_return true
    @cimg.stub(:process_image).and_return true
    @cimg.stub(:img).and_return true
  end

我的意思是,我从Factory.build获得的模型是完全有效的.但是,如果我不存根,它会将内容保存在文件系统中,并验证我未测试的内容...

I mean, the model I get from Factory.build is completely valid. But if I don't stub that stuff it saves things in the filesystem, and validates stuff I'm not testing...

我的意思是,我认为做这样的事情会更清洁:

What I mean, I think it would be cleaner to do something like this:

  before :each do
    @cimg = Factory.build :cimg_for_testing_tags
  end

如果甚至可以在工厂内进行存根.

If stubbing within the Factory is even possible.

对模型进行存根的正确方法是什么?

What is the proper way to stub the model?

推荐答案

在最新版本的factory_girl中,您有一个after_build回调,所以我相信您可以这样定义您的工厂:

In recent versions of factory_girl you have an after_build callback, so I believe you could define your factory like this:

FactoryGirl.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after_build do |cimg|
      cimg.stub(:validate_img).and_return true
    end
  end
end

更新

factory_girl 3.3.0之后,语法已更改为以下内容:

After factory_girl 3.3.0, the syntax has changed to following:

FactoryGirl.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after(:build) do |cimg|
      cimg.stub(:validate_img).and_return true
    end
  end
end

这篇关于我应该在测试时在Factory girl或spec文件中对模型进行存根处理吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆