junior
junior

Reputation: 808

Rails 4 minitest failed for update action

Im using Rails 4.1.6 and Ruby 2.1.3

my update method in bookmarks_controller.rb

def update
    service = UpdateBookmark.new(params[:id], params[:bookmark])

    if service.update
        head 204
    else
        head 422
    end
end

and this is my UpdateBookmark class under app/services directory:

class UpdateBookmark
    attr_reader :bookmark

    def initialize id, data
        @id = id
        @data = data
    end

    def update
        begin
            @bookmark = Bookmark.find @id
            @bookmark.update_attributes @data
        rescue
            false
        end
    end
end

Im using minitest for testing, and this is my bookmarks_controller_test.rb

test "returns ok if a record is updated" do
 bookmark = Bookmark.create! ({ title: "Tuts+", url: "http://tutsplus.com" })
 put :update, id: bookmark.id, bookmark: { title: "Net Tuts" }

 assert_response 204
end

and this is my update_bookmark_test.rb under test/services directory for testing my UpdateBookmark class

require 'test_helper'
require 'minitest/spec'

describe "UpdateBookmark" do
    it "updates a bookmark" do
        bookmark = Bookmark.create! title: "Tuts+", url: "http://tutsplus.com"
        service = UpdateBookmark.new(bookmark.id, { 
                                        title: "Net Tuts",
                                        url: "http://net.tutsplus.com"})
        service.update
        service.bookmark.title.must_equal "Net Tuts"
        service.bookmark.url.must_equal "http://net.tutsplus.com"
    end

    it "fails to create a bookmark if there's no id" do
        refute UpdateBookmark.new(nil, {}).update
    end
end

when I run my test, it fails as follow:

BookmarksControllerTest#test_returns_ok_if_a_record_is_updated [/home/krismp/Sites/dainty/api/test/controllers/bookmarks_controller_test.rb:21]:
Expected response to be a <204>, but was <422>.
Expected: 204
  Actual: 422

Why is that happen?

Upvotes: 0

Views: 381

Answers (1)

Pavel S
Pavel S

Reputation: 389

Your UpdateBookmark service suppresses all exceptions that can happen during update, so you are suffering from lack of information. I don't know who told you to place this begin ... rescue ... end statement but you should comment it out for a while so you can see much more information about what's wrong.

def update
  #begin
    @bookmark = Bookmark.find @id
    @bookmark.update_attributes @data
  #rescue
  #  false
  #end
end

P.S. In Ruby there is a common convention of using 2 spaces as indentation, not 4.

Upvotes: 2

Related Questions