<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Karim Marabet on Medium]]></title>
        <description><![CDATA[Stories by Karim Marabet on Medium]]></description>
        <link>https://medium.com/@mrabets?source=rss-77f5e41c7ca6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3vFj3UYEoCrCvIrwxt4-ZA.png</url>
            <title>Stories by Karim Marabet on Medium</title>
            <link>https://medium.com/@mrabets?source=rss-77f5e41c7ca6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:16:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrabets/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Run Ruby on Rails 7 App with Docker]]></title>
            <link>https://levelup.gitconnected.com/run-ruby-on-rails-7-app-with-docker-11c8ac1e9a0d?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/11c8ac1e9a0d</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 14:36:41 GMT</pubDate>
            <atom:updated>2023-11-29T10:20:30.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zbz9fpzWMO-of_GvfWyY4Q.png" /></figure><p>It’s no secret that Docker makes developer’s life easier. You and your teammates can run the application as a docker container whenever you want and don’t depend on a specific local machine. Unfortunately, in order to enjoy a Docker we need to exert a bit of action…</p><p>In this tutorial, I’ll show you how to easily run your simple Rails application (Postgres + Redis) with Docker and Docker Compose.</p><p>Let’s start!</p><h3>Step 1. Setup local environment</h3><p>I’ve already installed the latest present-day Ruby and Rails versions on my local machine.</p><pre>ruby -v<br>ruby 3.1.0p0 (2021-12-25 revision fb4df44d16) [x86_64-linux]<br><br>rails -v<br>Rails 7.0.4.2</pre><p>Initialize the app with Postgres</p><pre>rails new myapp -d postgresql</pre><p>Install <a href="https://github.com/bkeepers/dotenv">dotenv</a><em> </em>gem to use env variables in your app</p><pre>gem &#39;dotenv-rails&#39;</pre><p>Write to .env file your database credentials including host, because we’ll have 2 types of host: localhost and db (for Docker environment)</p><pre>DATABASE_USERNAME=&lt;your_db_username&gt;<br>DATABASE_PASSWORD=&lt;your_db_password&gt;<br>DATABASE_HOST=localhost</pre><p>Configure database.yml file with env variables</p><pre>default: &amp;default<br>  adapter: postgresql<br>  encoding: unicode<br>  host: &lt;%= ENV.fetch(&quot;DATABASE_HOST&quot;) %&gt;<br>  username: &lt;%= ENV.fetch(&quot;DATABASE_USERNAME&quot;) %&gt;<br>  password: &lt;%= ENV.fetch(&quot;DATABASE_PASSWORD&quot;) %&gt;<br>  pool: 5<br><br>development:<br>  &lt;&lt;: *default<br>  database: myapp_development<br><br>test:<br>  &lt;&lt;: *default<br>  database: myapp_test</pre><p>Create and migrate the database</p><pre>rails db:create db:migrate</pre><p>Run the server</p><pre>rails s</pre><p>If there are no errors, let’s continue with Docker 😋</p><h3>Step 2. Setup Docker environment</h3><p>To achieve our goal we should use docker-compose It requires 3 steps:</p><ol><li>Define the app environment with a <strong>Dockerfile</strong></li><li>Define the app services (ex. Rails app container + Postgres container + Redis container etc.) in <strong>docker-compose.yml</strong></li><li>Run <strong>docker-compose up</strong> to start and run the app</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*iSYQJv3obv1KuU4n.png" /><figcaption>I like this image as it visually shows docker-compose works</figcaption></figure><blockquote>A <em>Dockerfile</em> is just a text document that contains all the commands a user could call on the command line to assemble an image.</blockquote><p>The following steps are needed to collect the Rails app:</p><ul><li>Install Ruby from <a href="https://hub.docker.com/_/ruby">docker hub</a> (be attentive Ruby version shall be the same as in Gemfile).</li><li>Install all needed packages (you can choose whatever you need)</li><li>Choose work directory</li><li>Copy Gemfile and Gemfile.lock to work directory and install gems</li><li>Start the server with 3000 port</li></ul><p>So, Dockerfile should looks something like this</p><pre>FROM ruby:3.1.0<br><br>RUN apt-get update -qq &amp;&amp; apt-get install -y nodejs postgresql-client<br>WORKDIR /myapp<br>COPY Gemfile /myapp/Gemfile<br>COPY Gemfile.lock /myapp/Gemfile.lock<br>RUN bundle install<br><br>EXPOSE 3000<br><br>CMD [&quot;rails&quot;, &quot;server&quot;, &quot;-b&quot;, &quot;0.0.0.0&quot;]</pre><p>The next step is docker-compose.</p><p>In my case, I have 3 services:</p><ul><li>db (Postgres image with preset POSTGRES_PASSWORD variable)</li><li>redis</li><li>web (raw Rails app depends on db and redis with preset env variables)</li></ul><p>docker-compose.yml should looks something like this, but you can easily configure it for your needs:</p><pre>version: &#39;3.5&#39;<br>services:<br>  db:<br>    image: postgres<br>    volumes:<br>      - ./tmp/db:/var/lib/postgresql/data<br>    environment:<br>      POSTGRES_PASSWORD: password<br>  redis:<br>    image: redis<br>    command: redis-server<br>    volumes:<br>      - &#39;redis:/data&#39;<br>  web:<br>    build: .<br>    command: bash -c &quot;rm -f tmp/pids/server.pid &amp;&amp; bundle exec rails s -p 3000 -b &#39;0.0.0.0&#39;&quot;<br>    volumes:<br>      - .:/myapp<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - db<br>      - redis<br>    environment:<br>      - REDIS_URL_CACHING=redis://redis:6379/0<br>      - DATABASE_HOST=db<br>      - DATABASE_USERNAME=postgres<br>      - DATABASE_PASSWORD=password<br><br>volumes:<br>  redis:<br>  postgres:</pre><p>Note, DATABASE_HOST have to equal db (not localhost)!</p><p>Build the image, create &amp; migrate the database, and compose the app:</p><pre>docker-compose build<br>docker-compose run web rails db:create db:migrate<br>docker-compose up</pre><p>You can see your Rails app in the Docker environment by clicking <a href="http://0.0.0.0:3000/">http://0.0.0.0:3000/</a>. Congrats 🎉!</p><p>🎁 You can clone the GitHub repo <a href="https://github.com/mrabets/myapp-docker">https://github.com/mrabets/myapp-docker</a> and compose it.</p><p>Thank you for reading my tutorial. I would be glad for your feedback 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11c8ac1e9a0d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/run-ruby-on-rails-7-app-with-docker-11c8ac1e9a0d">Run Ruby on Rails 7 App with Docker</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write a simple Golang API Server?]]></title>
            <link>https://towardsdev.com/how-to-write-a-simple-golang-api-server-adc1fc0e652a?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc1fc0e652a</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 21:09:07 GMT</pubDate>
            <atom:updated>2022-04-29T08:00:56.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNjoIKCItsdUfljx5el7IQ.png" /></figure><p>I consider writing a web server to be a really good solution to learning a new language. Golang Developers often use the <a href="https://golang.org/pkg/net/http/">net/http</a> package to provide HTTP client and server implementations.</p><p>However, I decided to use an external package named gorilla/mux . I like it for more usability and simplicity.</p><p>Let’s get started!</p><h3>Step 1. Setup project</h3><p>Create a project folder and main.go file:</p><pre>mkdir blog-api<br>cd blog-api<br>touch main.go</pre><p>Then create a new repository on GitHub with blog-api name and initialize the <a href="https://www.digitalocean.com/community/tutorials/how-to-use-go-modules">go module</a>:</p><pre>go mod init github.com/&lt;your_github_username&gt;/blog-api</pre><p>And install needed dependencies:</p><pre>go get github.com/lib/pq<br>go get github.com/gorilla/mux</pre><p>pq is a Go postgres driver</p><p>gorilla/mux is a Package that implements a request router</p><p>Open the main.go file and write the simplest server:</p><pre>package main</pre><pre>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;</pre><pre>&quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br> r := mux.NewRouter()</pre><pre>r.HandleFunc(&quot;/posts&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  fmt.Fprintf(w, &quot;My Posts\n&quot;)<br> })</pre><pre>log.Fatal(http.ListenAndServe(&quot;:9090&quot;, r))<br>}</pre><p>Start the server:</p><pre>go run main.go</pre><p>And open the other terminal to test it:</p><pre>curl localhost:9090/posts</pre><h3>Step 2. Seed the database</h3><p>The database schema will be <em>ridiculously simple</em>. I did this so as not to spend a lot of time on <em>unimportant details</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*atZT6GKQYmUsIqO032nGiA.png" /></figure><blockquote>I assume that you have a Postgres installed and a user with a password created. If it’s not you can check <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-20-04">this</a> tutorial.</blockquote><p>Open the postgres environment:</p><pre>sudo -i -u postgres<br>=&gt; write your password<br>psql</pre><p>Create the database and table:</p><pre>CREATE DATABASE blogdb;<br>\c blogdb;</pre><pre>CREATE TABLE posts<br>(<br>    id serial primary key,<br>    title VARCHAR(80) not null,<br>    content TEXT not null<br>);</pre><p>And seed the database:</p><pre>insert into<br>    posts (title, content)<br>values<br>    (&#39;Etiam mattis risus quis&#39;,&#39;Vestibulum at iaculis mauris. Mauris fringilla id ipsum non euismod. Etiam tempus eleifend enim eu congue. Praesent ut leo tincidunt nisl semper sagittis. Sed varius eu mauris at vestibulum. Nunc a dapibus enim. Ut malesuada orci in nulla tincidunt malesuada.&#39;),<br>    (&#39;Aliquam lacinia mattis rhoncus&#39;,&#39;Vestibulum dapibus mi mauris, vel pretium nisi efficitur varius. Integer at lectus feugiat, laoreet diam sit amet, ultricies mauris. Donec molestie elit non urna convallis accumsan.&#39;),<br>    (&#39;Sed sit amet condimentum erat.&#39;,&#39;Nullam eget egestas tortor, eget condimentum dui. Duis facilisis risus quis fermentum laoreet. Phasellus placerat tempor justo vel tincidunt. Curabitur hendrerit justo at eleifend tempor. &#39;);</pre><h3>Step 3. Get posts from the database</h3><p>The final code to get posts from database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4c21622fb99999df539dfc72a8a7c10/href">https://medium.com/media/c4c21622fb99999df539dfc72a8a7c10/href</a></iframe><ul><li>type Post struct math the database table.</li><li>queryPosts connects to the database and selects all posts.</li><li>In getPosts I get posts from queryPosts and encode it.</li></ul><p>⚠️ Restart the server</p><p>Send the request:</p><pre>curl localhost:9090/posts</pre><p>At the output we should get JSON:</p><pre>[{&quot;id&quot;:1,&quot;title&quot;:&quot;Etiam mattis risus quis&quot;,&quot;content&quot;:&quot;Vestibulum at iaculis mauris. Mauris fringilla id ipsum non euismod. Etiam tempus eleifend enim eu congue. Praesent ut leo tincidunt nisl semper sagittis. Sed varius eu mauris at vestibulum. Nunc a dapibus enim. Ut malesuada orci in nulla tincidunt malesuada.&quot;},{&quot;id&quot;:2,&quot;title&quot;:&quot;Aliquam lacinia mattis rhoncus&quot;,&quot;content&quot;:&quot;Vestibulum dapibus mi mauris, vel pretium nisi efficitur varius. Integer at lectus feugiat, laoreet diam sit amet, ultricies mauris. Donec molestie elit non urna convallis accumsan.&quot;},{&quot;id&quot;:3,&quot;title&quot;:&quot;Sed sit amet condimentum erat.&quot;,&quot;content&quot;:&quot;Nullam eget egestas tortor, eget condimentum dui. Duis facilisis risus quis fermentum laoreet. Phasellus placerat tempor justo vel tincidunt. Curabitur hendrerit justo at eleifend tempor. &quot;}]</pre><p>I hope this tutorial gave some understanding of how to write a simple server in Go. See you in the next lessons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc1fc0e652a" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-write-a-simple-golang-api-server-adc1fc0e652a">How to write a simple Golang API Server?</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up MySQL with Ruby on Rails 7 on Ubuntu 20.04]]></title>
            <link>https://levelup.gitconnected.com/setting-up-mysql-with-ruby-on-rails-7-on-ubuntu-20-04-f6bbbb833db9?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6bbbb833db9</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 23:23:00 GMT</pubDate>
            <atom:updated>2022-04-24T23:23:00.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ug6yQp90qha7heZJSNHMA.png" /></figure><p><strong>MySQL</strong> is one of the most popular relational database system. Unlike Postgres, this is <strong>a purely relational database</strong>, and sometimes RoR developers prefer to use exactly it.</p><p>In this tutorial, I will show you how to install it, create a role and link the database with the Ruby on Rails application.</p><p>Let’s get started!</p><h3>Step 1. Installing MySQL</h3><pre>sudo apt-get update<br>sudo apt-get install mysql-server mysql-client libmysqlclient-dev</pre><p>mysql-server is a general database package.</p><p>mysql-client contains additional utilities and functionality.</p><p>libmysqlclient-dev use for compiling C programs communicate with MySQL.</p><h3>Step 2. Creating a user</h3><p>The command below designed to set a few initial parameters that are more secure than the default Ubuntu (and MySQL) installation.</p><pre>sudo mysql_secure_installation</pre><p>For the fastest setup, just press Enter step by step.</p><p>After that go into mysql environment:</p><pre>sudo mysql</pre><p>To create a new role enter the following command with your username (replace with yours) and password:</p><pre>CREATE USER &#39;&lt;your_username&gt;&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;&lt;your_password&gt;&#39;;</pre><p>Give all privileges to this user.</p><pre>GRANT ALL PRIVILEGES ON *.* TO &#39;&lt;your_username&gt;&#39;@&#39;localhost&#39; WITH GRANT OPTION;</pre><p>And run</p><pre>exit</pre><p>Now, try to enter intomysql environment with new user (and enter password):</p><pre>mysql -u &lt;your_username&gt; -p</pre><p>If it opens well exit from mysql environment again.</p><pre>exit</pre><h3>Step 3. Creating a Rails App</h3><pre>rails new app -d mysql<br>cd app</pre><p>Now install the <strong>MySQL adapter</strong> for Rails.</p><pre>gem install mysql2</pre><p>To store the secrets I’m using <a href="https://blog.saeloun.com/2019/10/10/rails-6-adds-support-for-multi-environment-credentials.html">credentials</a>.</p><pre>EDITOR=nano rails credentials:edit</pre><p>Add database username and password.</p><pre>database:<br>  username: &lt;your_username&gt;<br>  password: &lt;your_password&gt;</pre><p>Ctrl + X<strong> , </strong>Y and Enter .</p><p>Update the database.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1ab262870e25ed59a2dcc04a47fc4c/href">https://medium.com/media/aa1ab262870e25ed59a2dcc04a47fc4c/href</a></iframe><p>Create and migrate the database</p><pre>rails db:create db:migrate</pre><p>And the last step — start the server.</p><pre>rails s</pre><p>Hooray! 🎉 Hope the tutorial helped you to set up the MySQL with Rails. See you in the next tutorials.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6bbbb833db9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/setting-up-mysql-with-ruby-on-rails-7-on-ubuntu-20-04-f6bbbb833db9">Setting up MySQL with Ruby on Rails 7 on Ubuntu 20.04</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Testing React Apps]]></title>
            <link>https://medium.com/@mrabets/intro-to-testing-react-apps-3ae83b502814?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae83b502814</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 14:39:15 GMT</pubDate>
            <atom:updated>2022-03-24T12:27:16.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rqnu5_y-lYANRTXw" /><figcaption>Photo by <a href="https://unsplash.com/@filisantillan?utm_source=medium&amp;utm_medium=referral">Fili Santillán</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, I’ll use the most popular library for writing <strong>unit tests</strong> for React components. The React Testing Library is a very light-weight solution for testing React components. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages better testing practices.</p><h3>Step 1. Create the project</h3><p>Let’s start with creating the application using create-react-app command:</p><pre>npx create-react-app testing-app<br>cd testing-app</pre><p>And install react-testing-library :</p><pre>npm install --save @testing-library/react @testing-library/jest-dom</pre><h3>Step 2. Create the component</h3><p>To write the component test, you may follow any of the following popular naming conventions:</p><ul><li>Files with .js suffix in __tests__ folders.</li><li>Files with .test.js suffix.</li><li>Files with .spec.js suffix.</li></ul><p>Create the component src/components/CryptoList/CryptoList.jsx :</p><pre>const CryptoList = (props) =&gt; {<br>  const {cryptos = []} = props;</pre><pre>  return (<br>    &lt;ul&gt;<br>      {<br>        cryptos.map(c =&gt; (&lt;li key={c}&gt;{c}&lt;/li&gt;))<br>      }<br>    &lt;/ul&gt;<br>  )<br>}</pre><pre>export default CryptoList;</pre><h3>Step 3. Write the first unit test</h3><p>Let’s write the first test that checks for <em>list</em> and <em>text</em> on the screen.</p><p>Create the test file src/components/CryptoList/CryptoList.test.jsx :</p><pre>import { render, screen } from &#39;<a href="http://twitter.com/testing">@testing</a>-library/react&#39;;</pre><pre>import CryptoList from &#39;./CryptoList&#39;;</pre><pre>const cryptos = [&#39;BTC&#39;, &#39;ETH&#39;, &#39;USDT&#39;, &#39;SOL&#39;];</pre><pre>describe(&#39;CryptoList component&#39;, () =&gt; {<br>  it(&#39;CryptoList renders&#39;, () =&gt; {<br>    render(&lt;CryptoList cryptos={cryptos} /&gt;);</pre><pre>    expect(screen.getByRole(&#39;list&#39;)).toBeInTheDocument();<br>    expect(screen.getByText(&#39;BTC&#39;)).toBeInTheDocument();<br>  })<br>})</pre><p>getByRole(&#39;list&#39;) searches the list on the screen.</p><p>getByText(&#39;BTC&#39;) searches BTC text.</p><p>Run <em>all</em> tests:</p><pre>npm test</pre><p>Or the <em>specific</em> test:</p><pre>npm test src/components/CryptoList/CryptoList.test.jsx</pre><p>Output:</p><pre>Test Suites: 1 passed, 1 total<br>Tests:       1 passed, 1 total</pre><h3>Step 4. Apply TDD</h3><p>Test-Driven Development (<em>TDD</em>) is an approach to automated software testing that involves writing <strong>a failing test</strong> before writing the production code to make it pass.</p><p>Add another test:</p><pre>...<br>it(&#39;CryptoList renders without data&#39;, () =&gt; {<br>  render(&lt;CryptoList /&gt;);</pre><pre>  expect(screen.queryByRole(&#39;list&#39;)).toBeNull();<br>})</pre><p>You can read about Types of Queries <a href="https://testing-library.com/docs/queries/about#types-of-queries">here</a>.</p><p>Run the tests:</p><pre>npm test</pre><p>Output:</p><pre>Test Suites: 1 failed, 1 total<br>Tests:       1 failed, 1 passed, 2 total</pre><h4>Resolve the test</h4><p>Add the following line to CryptoList :</p><pre>if (!cryptos.length) return null;</pre><p>And run the tests again:</p><pre>npm test</pre><p>Output:</p><pre>Test Suites: 1 passed, 1 total<br>Tests:       2 passed, 2 total</pre><p>Resolved! 👍</p><h3>Step 5. Snapshot</h3><p>Snapshot tests are a very useful tool <strong>whenever you want to make sure your UI does not change unexpectedly.</strong></p><pre>it(&#39;CryptoList snapshot&#39;, () =&gt; {<br>  const view = render(&lt;CryptoList cryptos={cryptos} /&gt;);</pre><pre>  expect(view).toMatchSnapshot();<br>})</pre><p>Run the tests:</p><pre>npm test</pre><p>Output:</p><pre>Snapshots:   1 passed, 1 total<br>Time:        1.133 s</pre><p>Now <strong>change CryptoList component</strong> and run npm test again:</p><pre>Snapshots:   1 failed, 1 total<br>Time:        0.778 s, estimated 1 s</pre><p>To update snapshot, use the command below:</p><pre>npm test -- -u</pre><p>Output:</p><pre>Snapshots:   1 updated, 1 total<br>Time:        0.758 s, estimated 1 s</pre><p>The aim of snapshot testing is <strong>not to replace existing unit tests, but to provide additional value and make testing painless.</strong></p><p>It was a very brief tutorial that may help you <strong>to start to write </strong>the React unit tests react-testing-library . Good luck in work! 💪</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae83b502814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RSpec Mocks and Stubs]]></title>
            <link>https://medium.com/@mrabets/rspec-mocks-and-stubs-1cd0dec9a6f9?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd0dec9a6f9</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[stub]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 09:18:08 GMT</pubDate>
            <atom:updated>2022-03-04T09:18:08.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4nXGRIoGOdcD9IBm" /><figcaption>Photo by <a href="https://unsplash.com/@alesnesetril?utm_source=medium&amp;utm_medium=referral">Ales Nesetril</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Configure project</h3><p>Install needed gems and initialize RSpec files.</p><pre>gem install rspec<br>gem install faker</pre><pre>rspec --init</pre><h3>Initial test</h3><p>Create account.rb</p><pre>class Account<br>  attr_reader :name</pre><pre>  def initialize(username)<br>    <a href="http://twitter.com/name">@name</a> = username<br>  end</pre><pre>  def deposit(amount)<br>    sleep 1<br>    p &#39;Successfully deposit your account.&#39;</pre><pre>    { deposit_id: rand(100), status: :success }<br>  end<br>end</pre><p>Add to spec/spec_helper.rb</p><pre>require_relative &#39;account&#39;</pre><p>Create spec/account_spec.rb</p><pre>require &#39;faker&#39;</pre><pre>RSpec.describe Account do<br>  let(:account) { described_class.new(username) }<br>  let(:username) { Faker::Internet.username }<br>  let(:amount) { rand(1..100) }</pre><pre>  describe &#39;#deposit&#39; do<br>    it &#39;return new balance&#39; do<br>      expect(account.deposit(amount)).to include(status: :success)<br>    end<br>  end<br>end</pre><p>Run</p><pre>rspec</pre><p>Result</p><pre>&quot;Successfully deposit your account.&quot;<br>..</pre><pre>Finished in 1.67 seconds (files took 0.33267 seconds to load)<br>2 examples, 0 failures</pre><p>In this example, will assume that use <strong>a real request to the server</strong>.</p><h4>Why is it bad?</h4><p>There are many reasons. For example, tests <strong>performance loss</strong> or there is <strong>important data</strong> <strong>that cannot be changed</strong> or after data is saved, an HTTP request is sent to the server and is <strong>change an account balance </strong>in, for example, Stripe.</p><h3>Stub</h3><p>A <strong>stub </strong>only<strong> </strong>defines the result of the method.</p><p>Update spec/account_spec.rb</p><pre>require &#39;faker&#39;</pre><pre>RSpec.describe Account do<br>  let(:account) { described_class.new(username) }<br>  let(:username) { Faker::Internet.username }<br>  let(:amount) { rand(1..100) }</pre><pre>  before do<br>    allow(account)<br>      .to receive(:deposit)<br>      .with(amount)<br>      .and_return({ status: :success })<br>  end</pre><pre>  describe &#39;#deposit&#39; do<br>    it &#39;return new balance&#39; do<br>      expect(account.deposit(amount)).to include(status: :success)<br>    end<br>  end<br>end</pre><p>Run</p><pre>rspec</pre><p>Result</p><pre>..</pre><pre>Finished in 0.68312 seconds (files took 0.32367 seconds to load)<br>2 examples, 0 failures</pre><p>As you can see, <strong>the success status was received, but the real method wasn’t called and the request was bypassed</strong>. As a result, the needed data was received and can use.</p><h3>Mock</h3><p>Let’s update spec/account_spec.rb again.</p><pre>require &#39;faker&#39;</pre><pre>RSpec.describe Account do<br>  let(:account) { described_class.new(username) }<br>  let(:username) { Faker::Internet.username }<br>  let(:amount) { rand(1..100) }</pre><pre>  describe &#39;#deposit&#39; do<br>    it &#39;return new balance&#39; do<br>      expect(account)<br>        .to receive(:deposit)<br>        .with(amount)<br>        .and_return(status: :success)</pre><pre>      # account.deposit(amount)<br>    end<br>  end<br>end</pre><p>Run</p><pre>rspec</pre><p>Error</p><pre>Failures:</pre><pre>1) Account#deposit return new balance<br>     Failure/Error:<br>       expect(account)<br>         .to receive(:deposit)<br>         .with(amount)<br>         .and_return(status: :success)<br>     <br>       (#&lt;Account:0x000055c7471d80a8 <a href="http://twitter.com/name">@name</a>=&quot;twila_willms&quot;&gt;).deposit(86)<br>           expected: 1 time with arguments: (86)<br>           received: 0 times<br>     # ./spec/account_spec.rb:8:in `block (3 levels) in &lt;top (required)&gt;&#39;</pre><pre>Finished in 0.66428 seconds (files took 0.31786 seconds to load)<br>1 example, 1 failure</pre><pre>Failed examples:</pre><pre>rspec ./spec/account_spec.rb:7 # Account#deposit return new balance</pre><p>Uncomment account.deposit(amount)</p><pre>rspec</pre><p>Output</p><pre>.</pre><pre>Finished in 0.67872 seconds (files took 0.35864 seconds to load)<br>1 example, 0 failures</pre><p>So,<strong> mocks</strong> expect methods to be called, otherwise, it raises an error.</p><h3>How to test modules?</h3><p>Create module bitcoin.rb</p><pre>module Bitcoin<br>  def rate<br>    rand(30_000.0..60_000.0).round(1)<br>  end<br>end</pre><p>Add to spec/spec_helper.rb</p><pre>require_relative &#39;../bitcoin&#39;</pre><p>Create module spec/bitcoin_spec.rb</p><pre>RSpec.describe Bitcoin do<br>  let(:bitcoin) { Class.new { include Bitcoin }.new }<br>  let(:preferred_rate) { 40000.0 }<br>  <br>  before do<br>    allow(bitcoin).to receive(:rand).and_return(preferred_rate)<br>  end</pre><pre>  describe &#39;#rate&#39; do<br>    it &#39;return $40000.0 rate&#39; do<br>      expect(bitcoin.rate).to eq(preferred_rate)<br>    end<br>  end<br>end</pre><p>Run</p><pre>rspec</pre><p>Output</p><pre>..</pre><pre>Finished in 0.67599 seconds (files took 0.31613 seconds to load)<br>2 examples, 0 failures</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd0dec9a6f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ with Ruby]]></title>
            <link>https://medium.com/@mrabets/rabbitmq-with-ruby-7c764fb6b6e8?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c764fb6b6e8</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Fri, 11 Feb 2022 09:10:57 GMT</pubDate>
            <atom:updated>2022-02-11T09:10:57.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HJvLuyAUCPb6J-r3" /><figcaption>Photo by <a href="https://unsplash.com/@anyadiary?utm_source=medium&amp;utm_medium=referral">Waranya Mooldee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>RabbitMQ</strong> is a message-queueing software also known as a message broker. It enables asynchronous processing, meaning that it allows you to put a message in a queue without processing it immediately.</p><p>In this tutorial, I’ll show you how to send and receive a message through queue that I create in advance in the RabbitMQ panel.</p><h3>Setup RabbitMQ</h3><p>The easiest way to set up RabbitMQ is to use Docker. If you haven’t the docker check the manual <a href="https://docs.docker.com/engine/install/ubuntu/">here</a>.</p><p>Run the command below.</p><pre>sudo docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.9-management</pre><p>Go to <a href="http://localhost:15672/">http://localhost:15672/</a> and you’ll see the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*O2-xzybYwRFVE3tNCobi2g.png" /></figure><p>Enter the username and password guest , and log in.</p><h3>Add a new queue</h3><p>Go to the <strong>Queues</strong> tab and press to <strong>Add a new queue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*c33BEIkRo1v9DnJ_IpOBKg.png" /></figure><p>Name the queue, for example, <strong>dev-queue, </strong>and press the button below.</p><h3>Sending a message</h3><p>I’ll use the most popular Ruby RabbitMQ client <a href="https://github.com/ruby-amqp/bunny">bunny</a>.</p><p>Let’s install the gem.</p><pre>gem install bunny</pre><p>Create send.rb and add the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dafbf0d10d79676791edb52c60407b5/href">https://medium.com/media/4dafbf0d10d79676791edb52c60407b5/href</a></iframe><p>Run the program.</p><pre>ruby send.rb</pre><p>You’ll see.</p><pre>=&gt; Successfully sent</pre><p>Let’s check the message in the RabbitMQ panel.</p><p>Open the <strong>dev-queue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*tmOW0kE9OaRRQl01AKj3Bw.png" /></figure><p>Click on the <strong>Get messages </strong>tab below. And you’ll get <strong>Hello from Ruby! </strong>message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*_jymRRdozlcN-HN8LikriQ.png" /></figure><h3>Receiving the message</h3><p>Insert the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9268523f8235a9f0def69c52bcd1e3cc/href">https://medium.com/media/9268523f8235a9f0def69c52bcd1e3cc/href</a></iframe><p>Run the program.</p><pre>ruby receive.rb</pre><p>You’ll see the last message from dev-queue.</p><pre>=&gt; Hello from Ruby!</pre><h3>Conclusion</h3><p>It was a very simple example of working with RabbitMQ. Hope this tutorial will help you to start working with this technology using Ruby and Rails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c764fb6b6e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing a Rails API with RSpec]]></title>
            <link>https://blog.devgenius.io/testing-a-rails-api-with-rspec-82dedc9f15df?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/82dedc9f15df</guid>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 14:04:08 GMT</pubDate>
            <atom:updated>2022-02-08T14:04:08.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9iQIqnrcSFAsklJ" /><figcaption>Photo by <a href="https://unsplash.com/@quincoetzee?utm_source=medium&amp;utm_medium=referral">Quinton Coetzee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, I’ll show how to test the GET, POST, and DELETE methods of your Ruby on Rails API-only application using the most popular Ruby testing framework — RSpec.</p><p>At first, I’ll write the tests, that will fail, and then the controller’s code to solve the tests. In other words, I’ll use the <a href="https://en.wikipedia.org/wiki/Test-driven_development#:~:text=Test%2Ddriven%20development%20(TDD),software%20against%20all%20test%20cases.">TDD</a> approach.</p><p>Let’s code!</p><h3>Step 1. Create a Rails API</h3><p>In the beginning, create a simple Rails API-only application from scratch.</p><pre>rails new post-api --api -T<br>cd post-api</pre><p>Flag --api inherits ApplicationController from ActionController::API instead of ActionController::Base. It means that Action Controller provides modules used by browser apps and skip generating views, helpers, and assets that are not needed for our purpose.</p><p>We’re going to use <em>RSpec</em> instead of the <em>MiniTest</em>.The command -T skips the generation of Minitest::Unit files and folders.</p><h3>Step 2. Install gems</h3><p>Add rspec-rails to both the :development and :test groups of your app’s Gemfile . Also, add afactory_bot_rails gem for setting up test data objects and faker for generating fake data to the :test environment.</p><pre>group :development, :test do<br>  gem &#39;rspec-rails&#39;<br>end</pre><pre>group :test do<br>    gem &#39;factory_bot_rails&#39;<br>    gem &#39;faker&#39;<br>end</pre><p>Install.</p><pre>bundle</pre><h3>Step 3. Setup testing environment</h3><p>To finish RSpec installation use the command below.</p><pre>rails generate rspec:install</pre><p>The command generates a <em>spec</em> folder with rails_helper.rb , and spec_helper.rb files.</p><p>Next, create the <em>Post</em> factory with fake data in spec/factories.rb .</p><pre>FactoryBot.define do<br>  factory :post do<br>    title { Faker::Lorem.sentence }<br>    content { Faker::Lorem.paragraph }<br>  end<br>end</pre><p>To minimize a code, I’ll write a json method. It just parses a response body string. Let’s write it in spec/support/api_helpers.rb.</p><pre>module ApiHelpers<br>  def json<br>    JSON.parse(response.body)<br>  end<br>end</pre><p>The last thing to do is to require all support files and include the <em>ApiHelpers</em> module in spec/rails_helper.rb .</p><pre>Dir[Rails.root.join(&quot;spec/support/**/*.rb&quot;)].each { |f| require f }</pre><pre>RSpec.configure do |config|<br>  # ...<br>  config.include ApiHelpers<br>end</pre><h3>Step 4. API Specs</h3><p>I’ll use the <a href="https://www.freecodecamp.org/news/how-to-version-a-rest-api/#:~:text=so%20let&#39;s%20recap%3A-,API%20versioning%20is%20the%20practice%20of%20transparently%20managing%20changes%20to,effective%20API%20change%20management%20principles.">REST API Versioning</a>. It <strong>helps us iterate faster when the needed changes are identified in the APIs. </strong>It’s a best practice.</p><h4>GET</h4><p>Create spec/requests/get_posts_spec.rb and insert the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dcad0973a28a55920e5211e1dd3f380/href">https://medium.com/media/0dcad0973a28a55920e5211e1dd3f380/href</a></iframe><p>In the beginning, I use the FactoryBot method create_list to create 10 posts and then call an HTTP GET. next I check the size of created posts and HTTP status code.</p><h4>POST</h4><p>Next, create spec/requests/post_posts_spec.rb and insert it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ff78d4ad7c1acdf276031780efb4055/href">https://medium.com/media/9ff78d4ad7c1acdf276031780efb4055/href</a></iframe><p>I wrote a post instance inside let! method. Usually, if I need to use the instance below I use let! otherwise before .</p><h4>DELETE</h4><p>And the last one is to create spec/requests/delete_posts_spec.rb and insert the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e2fa10c227647d99109681a702512f2/href">https://medium.com/media/5e2fa10c227647d99109681a702512f2/href</a></iframe><p>Run the tests.</p><pre>rspec</pre><p>Tests must fail, let’s solve in the next step.</p><h3>Step 5. Pass the tests</h3><p>The first step to pass the tests is to <strong>generate a model <em>Post</em></strong>.</p><pre>rails g model Post title:string content:text --no-test-framework<br>rails db:migrate</pre><p>The --no-test-framework flag doesn’t create a model test. If you need model tests you can remove the flag.</p><p>The next step is to <strong>validate the model</strong>.</p><pre>class Post &lt; ApplicationRecord<br>  validates :title, :content, presence: true<br>end</pre><p>There is a validation only for the presence of the attribute.</p><p><strong>Build <em>Posts</em> controllers</strong> to satisfy all the testing requirements.</p><p>Create app/controllers/api/v1/posts_controller.rb file and insert the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d70f548f4f82bfc362bb0cb2b9501700/href">https://medium.com/media/d70f548f4f82bfc362bb0cb2b9501700/href</a></iframe><p>Update the routes.rb.</p><pre>Rails.application.routes.draw do<br>  namespace :api do<br>    namespace :v1 do<br>      resources :posts<br>    end<br>  end <br>end</pre><p>And run the tests again.</p><pre>rspec</pre><p>It works! 🥳 This was a very simple example that will give a starting point to write new tests for your API application. Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82dedc9f15df" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/testing-a-rails-api-with-rspec-82dedc9f15df">Testing a Rails API with RSpec</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Postgres with Ruby on Rails 7 on Ubuntu 20.04]]></title>
            <link>https://levelup.gitconnected.com/setting-up-postgres-with-ruby-on-rails-7-on-ubuntu-20-04-45ffd75e863d?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/45ffd75e863d</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 16:43:25 GMT</pubDate>
            <atom:updated>2022-01-20T16:43:25.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setting up Postgres with Ruby on Rails on Ubuntu 20.04</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hGBpaF3PE1uKHJGAA0A3g.png" /></figure><p><strong>Postgres</strong> is one of the most powerful databases that is widespread among Ruby on Rails developers. There are many advantages to using this database, for example, easier deploying to Heroku.</p><p>In this tutorial, I will show you how to install Postgres, create a role and link the database with the Ruby on Rails application.</p><p>Let’s get started!</p><h3>Step 1. Installing Postgres</h3><pre>sudo apt-get update<br>sudo apt install postgresql postgresql-contrib libpq-dev</pre><p>postgresql is a general database package.</p><p>postgresql-contrib contains additional utilities and functionality.</p><p>libpq-dev use for compiling C programs communicate with Postgres.</p><h3>Step 2. Creating a user</h3><p>The installation procedure created a user account called <strong>postgres</strong> that is associated with the default Postgres role.</p><p>Let’s switch to <strong>postgres </strong>account to access to <strong>psql</strong> — terminal-based Postgres front-end program.</p><pre>sudo -i -u postgres<br>psql</pre><p>Now there is postgres=# environment. To create a new role enter the following command.</p><pre>CREATE ROLE &lt;your_username&gt; LOGIN SUPERUSER PASSWORD &#39;&lt;your_password&gt;&#39;;</pre><pre># CREATE ROLE</pre><p><em>Superuser</em> bypasses all permission checks.</p><p>To list all users.</p><pre>\du</pre><p>Exit from <strong>psql</strong> and <strong>postgres</strong> environment using the command below.</p><pre>exit</pre><h3>Step 3. C<strong>reating</strong> a <strong>Rails App</strong></h3><pre>rails new app -d postgresql<br>cd app<br>bundle</pre><p>To store the secrets I will use credentials.</p><pre>EDITOR=nano rails credentials:edit</pre><p>Add database username and password.</p><pre>database:<br>  username: &lt;your_username&gt;<br>  password: &lt;your_password&gt;</pre><p>Ctrl + X<strong> , </strong>Y and Enter .</p><p>Update the database.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd972cc1d6ab4274e7278b05b95a0da8/href">https://medium.com/media/fd972cc1d6ab4274e7278b05b95a0da8/href</a></iframe><p>Create and migrate the database</p><pre>rails db:create db:migrate</pre><p>And start the server.</p><pre>rails s</pre><h3>Bonus: Switch from SQLite to Postgres</h3><p>Sometimes, you need to switch from one database to another. To do this follow these simple steps.</p><h4>Update Gemfile</h4><p>Delete SQLite gem from Gemfile.</p><pre>gem &#39;sqlite3&#39;</pre><p>And add Postgres gem.</p><pre>gem &#39;pg&#39;</pre><p>Run bundle.</p><pre>bundle</pre><p>Setup credentials and replace database.yml follow to instructions above.</p><p>If you have migrations files replace columns with t.string to t.text .</p><p>The last step is to create a new database.</p><pre>rails db:setup db:migrate</pre><p>Hooray! 🎉 Hope the tutorial helped you to set up the Postgres with Rails. Good luck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ffd75e863d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/setting-up-postgres-with-ruby-on-rails-7-on-ubuntu-20-04-45ffd75e863d">Setting up Postgres with Ruby on Rails 7 on Ubuntu 20.04</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy a Rails 7 App with Postgres to Heroku]]></title>
            <link>https://medium.com/@mrabets/how-to-deploy-a-rails-7-app-with-postgres-to-heroku-6a49db8328fd?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a49db8328fd</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 17:07:55 GMT</pubDate>
            <atom:updated>2022-01-20T07:16:04.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMMfxCz0kJk8BpJWH-SJJg.jpeg" /></figure><p><em>Heroku</em> allows you to quickly deploy your Ruby on Rails application. <em>Postgres</em> database is easier to deploy in Heroku than other databases.</p><p>In brief, Heroku handles pretty much everything for you, but it can be a disadvantage if you want to understand the deploying process in more detail.</p><p>In this tutorial, I will show you how to deploy a simple Ruby on Rails 7 CRUD application.</p><h3>Step 1. Creating a Rails App</h3><p>I will use a <a href="https://tailwindcss.com/">Tailwind CSS</a> as a frontend to not be very sad.</p><pre>rails new app -d postgresql<br>cd app<br>bundle a tailwindcss-rails<br>rails tailwindcss:install</pre><p><strong>Setting up database</strong></p><p>Update the database.yml with your data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fcb25525ed173d16d6e386988c2881a/href">https://medium.com/media/0fcb25525ed173d16d6e386988c2881a/href</a></iframe><p>As you can see, I use <em>environment variables</em>. Alternatively, you can use a newer Rails feature — <a href="https://blog.saeloun.com/2019/10/10/rails-6-adds-support-for-multi-environment-credentials.html">credentials</a>.</p><p>To use environment variables, add dotenv-rails to Gemfile.</p><pre>gem &#39;dotenv-rails&#39;, groups: [:development, :test]</pre><p>Run bundle.</p><pre>bundle</pre><p>Create .env in the project root and insert your data.</p><pre>DATABASE_USERNAME=myusername<br>DATABASE_PASSWORD=mypassword<br>DATABASE_HOST=localhost</pre><h4>Scaffolding post</h4><pre>rails g scaffold posts title:string content:text</pre><p>Create/migrate the database.</p><pre>rails db:create db:migrate</pre><p>Change the main page route in routes.rb .</p><pre>root &quot;posts#index&quot;</pre><p>And start the server.</p><pre>rails s</pre><h3>Step 2. Deploying</h3><p>First, you need to register the Heroku account.</p><p>Then install the <em>Heroku CLI.</em></p><pre>sudo snap install --classic heroku</pre><p>And login.</p><pre>heroku login</pre><h4>Create an app in Heroku</h4><p>The easiest way to create an application in Heroku is to run the following command.</p><pre>heroku create</pre><p><em>You can create it on the website if you want.</em></p><p>Push your commit to the Heroku app.</p><pre>git add .<br>git commit -m &quot;My first commit&quot;<br>git push heroku main</pre><h3>Step 3. Testing</h3><p>Migrate the database and start the server.</p><pre>heroku run rails db:migrate<br>heroku ps:scale web=1</pre><p>Running heroku ps:scale web=1 will scale your app to one running <a href="https://devcenter.heroku.com/articles/dynos">dyno</a>. That is, you have one server running.</p><p>Let’s open the deploying application.</p><pre>heroku open</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7npmV02qw2EqJilw6AlbQ.png" /><figcaption>Main page</figcaption></figure><p>And create a new post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBb1QmvdJ8MonfQ1twJjsw.png" /><figcaption>After post creation</figcaption></figure><p>Congrats, We did it! 🎉 I hope you got something useful from this short tutorial. Good luck.</p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/how-to-create-a-rails-6-api-with-devise-jwt-46fa35085e85">How to Create a Rails 6 API with Devise-JWT</a></li><li><a href="https://enlear.academy/the-top-5-most-popular-backend-frameworks-for-2022-9fbb8d07cca5">The Top 5 Most Popular Backend Frameworks for 2022</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a49db8328fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Rails App on DigitalOcean Droplet]]></title>
            <link>https://levelup.gitconnected.com/deploy-rails-app-on-digitalocean-droplet-ca60cd3b84c0?source=rss-77f5e41c7ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca60cd3b84c0</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[deploy]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Karim Marabet]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 23:36:51 GMT</pubDate>
            <atom:updated>2023-01-18T11:55:38.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Rails App on DigitalOcean Droplet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQFXeIUoRXpoS3X1VOd_PQ.png" /></figure><p><em>Digital Ocean</em> provides an easy-to-use, developer-centric platform, has lower costs, and has more data centers available. <em>DigitalOcean Droplets</em><strong><em> </em></strong>are simple, scalable virtual machines. Each Droplet you create is a new server you can use, either standalone or as part of a larger, cloud-based infrastructure.</p><p>First of all, we create simple Ruby on Rails application and then create a droplet, install necessary packages and gems, set up Postgres and host the application.</p><h3>Creating Rails App</h3><pre>rails new app -d postgresql<br>cd app</pre><p>Configure <em>database.yml</em> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fcb25525ed173d16d6e386988c2881a/href">https://medium.com/media/0fcb25525ed173d16d6e386988c2881a/href</a></iframe><p>As you can see I use environment variables and use it you need to install the <em>dotenv-rails</em> gem</p><pre>gem &#39;dotenv-rails&#39;, groups: [:development, :test]<br>bundle</pre><p>and create a .env file in the root directory and paste your data</p><pre>DATABASE_USERNAME=&lt;username&gt;<br>DATABASE_PASSWORD=&lt;password&gt;<br>DATABASE_HOST=localhost</pre><p>For more visibility let’s generate a scaffold and migrate the database</p><pre>rails g scaffold posts title:string content:text<br>rails db:setup<br>rails s</pre><p>I will place my app in <a href="https://github.com/">GitHub</a>. For that, I create a new repository, link it with my project, add secret information to <em>.gitignore</em> and push a commit.</p><pre>git remote add origin &lt;your_repo_link&gt;<br>git branch -M main<br>echo &quot;.env&quot; &gt;&gt; .gitignore<br>git add .<br>git commit -m &quot;Init commit&quot;<br>git push -u origin main</pre><h3>Setup DigitalOcean Droplet</h3><p>I guess you register the account in <a href="https://www.digitalocean.com/">DigitalOcean</a> and are ready to create a droplet. So, I chose Ubuntu 20.04 image and the most basic plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KYc70VyPkXOQcXvIWMM_w.png" /></figure><p>To speed up the creation process I set a password instead of SSH keys, but it is <em>not recommended</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ga-sXDLisM3f4e6TPGvrtw.png" /></figure><p>In a few minutes, the droplet will finish the installation and we can open the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QjDxzBAJk2n0w2AqQQ-Fg.jpeg" /></figure><p>When the console opens let’s start to set up the environment. Note that you have selected the required Ruby and Rails versions. You can check with ruby -v and rails -v commands in your project.</p><h4>Installing Ruby using RVM</h4><p>Enter the following commands in the droplet’s console.</p><pre>sudo apt update<br>sudo apt-get install software-properties-common<br>sudo apt-add-repository -y ppa:rael-gc/rvm<br>sudo apt-get update<br>sudo apt-get install rvm</pre><p>⚠️ Reboot the console.</p><pre>rvm install &lt;ruby_version&gt;<br>rvm --default use &lt;ruby_version&gt;</pre><h4>Installing Rails and dependencies</h4><pre>sudo apt install nodejs npm<br>npm install --global yarn<br>gem install bundler<br>gem install rails -v &lt;rails_version&gt;</pre><h4>Installing Postgres</h4><p>Note that you have selected the same database username as in the .env file</p><pre>sudo apt install postgresql postgresql-contrib libpq-dev<br>sudo -u postgres createuser --interactive</pre><pre># Enter name of role to add: &lt;database_username&gt;<br># Shall the new role be a superuser? (y/n)y</pre><pre>sudo -u postgres psql -c &quot;ALTER USER &lt;username&gt; PASSWORD &#39;&lt;database_password&gt;&#39;;&quot;</pre><pre># ALTER ROLE</pre><h4>Cloning and launching the project</h4><p>Clone the project and create a .env file in the root directory</p><pre>git clone &lt;your_repo_link&gt;<br>cd &lt;your_repo_name&gt;<br>nano .env</pre><p>and paste your data again</p><pre>DATABASE_USERNAME=&lt;username&gt;<br>DATABASE_PASSWORD=&lt;password&gt;<br>DATABASE_HOST=localhost</pre><p>The final step is creating a database, precompiling assets (optionally), and starting the server with binds to the droplet’s IP.</p><pre>bundle<br>rails db:setup<br>rails assets:precompile<br>rails s -b 0.0.0.0</pre><p>Check your ipv4 and paste it into your browser with 3000 port. In my case: <em>147.182.136.41:3000</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lgpm3HXvJqIckz0V7YqlIA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjXRAXhS-43JfveNPTe5eg.png" /></figure><p>Hooray! 🎉 It was not quite easy, but I hope that you extracted something useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca60cd3b84c0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/deploy-rails-app-on-digitalocean-droplet-ca60cd3b84c0">Deploy Rails App on DigitalOcean Droplet</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>