&tag(Railsテスティングガイド);
$ ls -F test controllers/ helpers/ mailers/ system/ test_helper.rb fixtures/ integration/ models/ application_system_test_case.rb
$ bin/rails generate model article title:string body:text ... create app/models/article.rb create test/models/article_test.rb create test/fixtures/articles.yml ...
require 'test_helper' class ArticleTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
test "the truth" do assert true end def test_the_truth assert true end
test "should not save article without title" do article = Article.new assert_not article.save end
$ bin/rails test test/models/article_test.rb
class Article < ApplicationRecord validates :title, presence: true end
$ bin/rails test test/models/article_test.rb $ bin/rails test test/models/article_test.rb -n test_the_truth $ bin/rails test test/models/article_test.rb:6 #行番号の指定 $ bin/rails test test/controllers #ディレクトリ
# lo & behold! I am a YAML comment! david: name: David Heinemeier Hansson birthday: 1979-10-15 profession: Systems development steve: name: Steve Ross Kellock birthday: 1974-09-27 profession: guy with keyboard
# In fixtures/categories.yml about: name: About # In fixtures/articles.yml first: title: Welcome to Rails! body: Hello world! category: about
# this will return the User object for the fixture named david users(:david) # this will return the property for david called id users(:david).id # one can also access methods available on the User class david = users(:david) david.call(david.partner)
$ bin/rails generate test_unit:model article title:string body:text create test/models/article_test.rb create test/fixtures/articles.yml
$ bin/rails generate system_test users
require "application_system_test_case" class UsersTest < ApplicationSystemTestCase # test "visiting the index" do # visit users_url # # assert_selector "h1", text: "Users" # end end
require "test_helper" require "capybara/poltergeist" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :poltergeist end class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :selenium, using: :firefox end class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :selenium, using: :headless_chrome end
$ bin/rails generate system_test articles
require "application_system_test_case"
class ArticlesTest < ApplicationSystemTestCase
test "viewing the index" do
visit articles_path
assert_selector "h1", text: "Articles"
end
end
bin/rails test:system
★chromedriverが存在しないと実行できない。macOSの場合「brew cask install chromedriver」でインストール可能。
test "creating an article" do visit articles_path click_on "New Article" fill_in "Title", with: "Creating an Article" fill_in "Body", with: "Created this article successfully!" click_on "Create Article" assert_text "Creating an Article" end
$ bin/rails generate integration_test user_flows
require 'test_helper' class UserFlowsTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end end
$ bin/rails generate integration_test blog_flow
require 'test_helper'
class BlogFlowTest < ActionDispatch::IntegrationTest
test "can see the welcome page" do
get "/"
assert_select "h1", "Welcome#index"
end
end
bundle exec rails generate controller Welcome index
Rails.application.routes.draw do get 'welcome/index' root 'welcome#index' resources :articles end
test "can create an article" do
get "/articles/new"
assert_response :success
post "/articles",
params: { article: { title: "can create", body: "article successfully." } }
assert_response :redirect
follow_redirect!
assert_response :success
assert_select "p", "Title:\n can create"
# assert_select "p" do |element|
# # 該当するNokogiri::XML::NodeSetがかえってくる(この場合3つの"p"要素のNokogiri::XML::Elementを含む)
# # textでタグを除いた状態のテキストが取得できる。これとの比較になる。
# p element.text
# end
end
$ bin/rails generate scaffold_controller article title:string
$ bin/rails generate test_unit:scaffold article
# articles_controller_test.rb
class ArticlesControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get articles_url
assert_response :success
end
end
get article_url, params: { id: 12 }, headers: { "HTTP_REFERER" => "http://example.com/home" }
patch article_url, params: { id: 12 }, xhr: true
test "should create article" do
assert_difference('Article.count') do
post articles_url, params: { article: { body: 'Rails is awesome!', title: 'Hello Rails' } }
end
assert_redirected_to article_path(Article.last)
end
test "ajax request" do article = articles(:one) get article_url(article), xhr: true assert_equal 'hello world', @response.body assert_equal "text/javascript", @response.content_type end
flash["gordon"] flash[:gordon] session["shmession"] session[:shmession] cookies["are_good_for_u"] cookies[:are_good_for_u]
class ArticlesControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get articles_url
assert_equal "index", @controller.action_name
assert_equal "application/x-www-form-urlencoded", @request.media_type
assert_match "Articles", @response.body
end
end
# setting an HTTP Header
get articles_url, headers: { "Content-Type": "text/plain" } # simulate the request with custom header
# setting a CGI variable
get articles_url, headers: { "HTTP_REFERER": "http://example.com/home" } # simulate the request with custom env variable
test "should create article" do
assert_difference('Article.count') do
post article_url, params: { article: { title: 'Some title' } }
end
assert_redirected_to article_path(Article.last)
assert_equal 'Article was successfully created.', flash[:notice]
end
def create
@article = Article.new(article_params)
if @article.save
flash[:notice] = 'Article was successfully created.'
redirect_to @article
else
render 'new'
end
end
test "should show article" do article = articles(:one) get article_url(article) assert_response :success end
test "should destroy article" do
article = articles(:one)
assert_difference('Article.count', -1) do
delete article_url(article)
end
assert_redirected_to articles_path
end
test "should update article" do
article = articles(:one)
patch article_url(article), params: { article: { title: "updated" } }
assert_redirected_to article_path(article)
# Reload association to fetch updated data and assert that title is updated.
article.reload
assert_equal "updated", article.title
end
module SignInHelper
def sign_in_as(user)
post sign_in_url(email: user.email, password: user.password)
end
end
class ActionDispatch::IntegrationTest
include SignInHelper
end
require 'test_helper'
class ProfileControllerTest < ActionDispatch::IntegrationTest
test "should show profile" do
# helper is now reusable from any controller test case
sign_in_as users(:david)
get profile_url
assert_response :success
end
end
assert_select 'title', "Welcome to Rails Testing Guide"
assert_select 'ul.navigation' do assert_select 'li.menu_item' end
assert_select "ol" do |elements|
elements.each do |element|
assert_select element, "li", 4
end
end
assert_select "ol" do
assert_select "li", 8
end
module UserHelper
def link_to_user(user)
link_to "#{user.first_name} #{user.last_name}", user
end
end
class UserHelperTest < ActionView::TestCase
test "should return the user's full name" do
user = users(:david)
assert_dom_equal %{<a href="/user/#{user.id}">David Heinemeier Hansson</a>}, link_to_user(user)
end
require 'test_helper'
class UserMailerTest < ActionMailer::TestCase
test "invite" do
# Create the email and store it for further assertions
email = UserMailer.create_invite('[email protected]',
'[email protected]', Time.now)
# Send the email, then test that it got queued
assert_emails 1 do
email.deliver_now
end
# Test the body of the sent email contains what we expect it to
assert_equal ['[email protected]'], email.from
assert_equal ['[email protected]'], email.to
assert_equal 'You have been invited by [email protected]', email.subject
assert_equal read_fixture('invite').join, email.body.to_s
end
end
Hi [email protected], You have been invited. Cheers!
require 'test_helper'
class UserControllerTest < ActionDispatch::IntegrationTest
test "invite friend" do
assert_difference 'ActionMailer::Base.deliveries.size', +1 do
post invite_friend_url, params: { email: '[email protected]' }
end
invite_email = ActionMailer::Base.deliveries.last
assert_equal "You have been invited by [email protected]", invite_email.subject
assert_equal '[email protected]', invite_email.to[0]
assert_match(/Hi friend@example\.com/, invite_email.body.to_s)
end
end
require 'test_helper'
class BillingJobTest < ActiveJob::TestCase
test 'that account is charged' do
BillingJob.perform_now(account, product)
assert account.reload.charged_for?(product)
end
end
require 'test_helper'
class ProductTest < ActiveJob::TestCase
test 'billing job scheduling' do
assert_enqueued_with(job: BillingJob) do
product.charge(account)
end
end
end
# Lets say that a user is eligible for gifting a month after they register. user = User.create(name: 'Gaurish', activation_date: Date.new(2004, 10, 24)) assert_not user.applicable_for_gifting? travel_to Date.new(2004, 11, 24) do assert_equal Date.new(2004, 10, 24), user.activation_date # inside the `travel_to` block `Date.current` is mocked assert user.applicable_for_gifting? end assert_equal Date.new(2004, 10, 24), user.activation_date # The change was visible only inside the `travel_to` block.