开发者

Are these controller specs good enough?

开发者 https://www.devze.com 2023-03-17 11:58 出处:网络
I am new to testing controllers with RSpec. In my controller, I have these methods: def edit @widget = Widget.find(params[:id])

I am new to testing controllers with RSpec. In my controller, I have these methods:

  def edit
    @widget = Widget.find(params[:id])
    if @widget.present?
      @all_widgets = Widget.where(:id != @widget.id).select("id, title")
      wfs @widget.id
    else
      redirect_to widgets_url
    end
  end

and

  def wfs widget_id
    @all_features,
    @existing_features,
    @draft_features,
    @imported_features  = WidgetFeature.find_by_widget_id_group_by_status(widget_id)
  end

I have tested the method WidgetFeature.find_by_widget_id_group_by_status(widget_id) in the corresponding model.

Now, I don't know how to test the edit method and what to test. I know all about stubs, mocks and doubles. I am following the Rails Test Prescriptions and the RSpec book. So, I am familiar with the terminology and the basics, however I am confused when to mock or make a factory for the data.

Also, how do I test that the edit method actually calls the wfs method?

UPDATE:

These are some specs I have written, that give 100% coverage (tested by SimpleCov). Is this the best way to test the above methods.

  context " When #edit is called, it" do
    it "assigns @all_widgets & other variables if widget for given widget_id is present" do
      widget = Factory.create(:widget)
      get :edit, :id => widget.id
      assigns.each {|a| a.sho开发者_运维百科uld be_kind_of(Array)}
      response.should be_success
      response.should render_template("edit")
    end
    it "redirects_to widgets_url if widget for given widget_id is not present" do
      widget = Widget.stub!(:find).with(12)
      get :edit, :id => 12
      response.should redirect_to(widgets_url)
      response.should be_redirect
    end
  end

Comments are welcome on how to improve the above specs


You should mock WidgetFeature. In that way tests will be faster as it does not hit DB. And to check whether edit method is calling wfs method, you can use should_receive.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号