测试 标题讲不清呀我操...

snowhs · 2013年01月30日 · 最后由 zchar 回复于 2013年01月30日 · 2177 次阅读

设我们有

# app/controllers/posts_controller.rb
class PostsController
  def create
  end

  def index
  end
end

这时候为了测试Post.create之后posts#index有相应更新,有两个方法。 一个是

# spec/controllers/posts_controller_spec.rb
describe PostsController do
  describe :index do
    before do
      Post.create content: 'Lorem lipsm'
    end

    specify do
      get :index
      expect(respond).to be_success
    end
  end
end

另一个是

# spec/controllers/posts_controller_spec.rb
describe PostsController do
  describe :index do
    before do
      post :create, content: 'Lorem lipsm'
    end

    specify do
      get :index
      expect(respond).to be_success
    end
  end
end

后者可以连带posts#create一起测了。 在各位看来,两者各有什么优劣呢?

在大多情况下下面一句话测试不了 create 这个 action 吧,应该会有些其它的情形 (针对非法数据之类的), 所以针对 create 的测试是肯定要再写一次的

post :create, content: 'Lorem lipsm' 

那么,你喜欢 create 这个 action 有 bug 后,出一堆错误呢?还是只想让测试 create 的测试出错?

#1 楼 @zhangjinzhu 问得好!

我倾向于错误尽早被发现,因此希望posts#create有bug的时候,所有相关的,哪怕是间接相关的测试,都失败。

最好是分开吧,各自做各自的事情

需要 登录 后方可回复, 如果你还没有账号请 注册新账号