Reputation: 1592
I am testing a controller. Index just method saves article to activerecord but i cannot get the article from test code.
What am I missing?
Controller
class ArticlesController < ApplicationController
def create
if Article.new(:title => "abc").save
render status: 200, json: ""
else
render status: 500, json: ""
end
end
end
Test
require 'test_helper'
class ArticlesControllerTest < ActionController::TestCase
test "should get create" do
get :create
assert_response :success
assert_nil Article.where(title: "abc"), "Article nil"
end
end
I get following result
F
Finished in 0.100930s, 9.9079 runs/s, 19.8157 assertions/s.
1) Failure:
ArticlesControllerTest#test_should_get_index [test/controllers/articles_controller_test.rb:7]:
Article nil.
Expected #<ActiveRecord::Relation [#<Article id: 980190963, title: "abc", created_at: "2016-06-24 13:23:36", updated_at: "2016-06-24 13:23:36">]> to be nil.
1 runs, 2 assertions, 1 failures, 0 errors, 0 skips
Upvotes: 0
Views: 41
Reputation: 3847
Just look at your code and your test.
You have a GET#create
call, where you do indeed create an Article object with the title 'abc'.
Then in your test, you call this action, which will create the Article with 'abc' as title, and then do this assertion:
assert_nil Article.where(title: "abc"), "Article nil"
Which fails, and it should, because there is an Article with 'abc' as a title (You just created it in you controller).
What your're doing is the wrong assertion. You don't want to assert_nil the article, you want to make sure that he is there, hence not nil.
Something like:
class ArticlesControllerTest < ActionController::TestCase
test "should get create" do
get :create
assert_response :success
refute_nil Article.where(title: "abc").first, "Article should not be nil"
end
end
Aside this problem Article.where will not return you nil if it finds no article. It will give you an empty ActiveRecord::Relation (#<ActiveRecord::Relation []>
)
Upvotes: 1
Reputation: 181
You are actually receiving the created Article record. Look at the last line of your test output. It says "Expected #ActiveRecord...", which means it returned an Article object but it was supposed to not return anything (nil).
The problem with you test code is your assertion line. assert_nil is the wrong method to use in this case.
Try something like:
assert_equal "abc", Article.first.title
Upvotes: 1