Difference between revisions of "Ruby on Rails"

From wiki.jasonsnotes.com
Jump to navigation Jump to search
(quire ")
 
(One intermediate revision by the same user not shown)
Line 32: Line 32:
/app/tests/header_component_test.rb
/app/tests/header_component_test.rb


re
require "test_helper"
 
class HeaderComponentTest < ViewComponent::TestCase
 
  def test_renders_title
    expected = "TestTitle"
    render_inline HeaderComponent.new(expected)
    assert_text(expected)
  end
 
end
 
Test with `rails test`

Latest revision as of 16:31, 6 November 2025

View Components

(this is faster than partials, because it's plain ruby code)

bundle add view_component

rails g component header title (creates) /app/components/header_component.rb /app/test/header_component_test.rb /app/components/header_component.html.erb

/app/views/pages/home.html.erb:

<%= render(HeaderComponent.new("Hello World")) do %> This content will be inserted into the Header Component!! <% end %>

/app/components/header_component.rb:

Class HeaderComponent < ViewComponent::Base

 def initialize(title)
   @title = title
 end

end

/app/components/header_component.html.erb:

<%= @title %>

<%= content %>

/app/tests/header_component_test.rb

require "test_helper"

class HeaderComponentTest < ViewComponent::TestCase

 def test_renders_title
   expected = "TestTitle"
   render_inline HeaderComponent.new(expected)
   assert_text(expected)
 end

end

Test with `rails test`