teleren/devto huggingface dataset:
49 Days of Ruby: Day 46 -- Testing Frameworks: Minitest
Tags: ruby
Published: 2021-05-12 04:27:01

---
title: 49 Days of Ruby: Day 46 -- Testing Frameworks: Minitest
published: true
description: Join us on a 49 day learning journey through Ruby!
series: 49 Days of Ruby
tags: #ruby
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/9m73qaetuse3nm3y3it8.png
---

**Welcome to day 46 of the 49 Days of Ruby! 🎉**

Yesterday, we discussed *why* it is a good idea to write tests. Today, we'll talk a bit about how to do that using the Ruby testing framework, Minitest.

Let's see we had the following code:

```ruby
def my_coffee
  "Espresso"
end
```

Now, above is a pretty straightforward piece of Ruby code. The method outputs the string `Espresso`. 

What would a Minitest look like for this method?

```ruby
require "minitest/autorun"

 def test_that_coffee_is_espresso
    assert_equal "Espresso", my_coffee
end
```

In the above testing method, `#test_that_coffee_is_espresso` we invoke the Minitest `assert_equal`, which takes in two arguments. The arguments are the items being compared to each other. In this case, we are comparing what I expect the output to be, and what the method returns.

When you run this test, your terminal will show you something like this:

```bash
# Running:

...................................................................... (etc)

Finished in 0.107130s, 1 runs/s, 1 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
```

Meaning, your test passed!

## TDD

There is a very worthwhile way of writing code called "TDD," which stands for "Test Driven Development". It is the idea that you first write the tests, defining your code's expectations, and then write the code to match those tests.

Here is an example:

```ruby
def test_that_coffee_is_not_tea
  assert_not_equal, "Earl Gray", my_coffee
end

def test_that_coffee_is_espresso
  assert_equal, "Espresso", my_coffee
end
```

When you run that test initially you'll see an output including the following:

```bash
1 run, 2 assertions, 2 failures, 0 errors, 0 skips
```

The tests failed because there was no method called `#my_coffee`.

Those tests start to give us the contours of our as of yet undefined method. Now, when we want to start writing our code, we know that it should not be "Earl Gray" and it should be "Espresso":

```ruby
def my_coffee
  "Espresso"
end
```

Those are just a few examples of what you can do with Minitest! Check out their [README](https://github.com/seattlerb/minitest) on GitHub and keep on exploring.

**Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag [#49daysofruby](https://twitter.com/hashtag/49daysofruby).**
Treating warnings as errors because process.env.CI = true.
Tags: vercel
Published: 2021-05-12 04:20:40

This error happened everytime I deploy my react code to vercel. I solved this error by put this on scripts.
put this thing on your package.json, when you see 
``` javascript
CI=false npm run build
```

Don't put quotation as a string on env variable -vercel
``` javascript
scripts: {
  "build": "GENERATE_SOURCEMAP=false react-scripts build"
}
```

There is also a built-in environment variable called NODE_ENV. You can read it from `process.env.NODE_ENV`. When you run npm start, it is always equal to `'development'`, when you run npm test it is always equal to 'test', and when you run npm run build to make a production bundle, it is always equal to 'production'. You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.
Node.js : Reading from a file synchronously
Tags: node, programming, webdev, javascript
Published: 2021-05-12 03:57:22

For any file operations, you will need the filesystem module:
```javascript
const fs = require('fs');
```

# Reading a String
`fs.readFileSync` behaves similarly to `fs.readFile`, but does not take a callback as it completes synchronously and therefore blocks the main thread. Most node.js developers prefer the asynchronous variants which will cause virtually no delay in the program execution.

If an encoding option is specified, a string will be returned, otherwise a Buffer will be returned.
```javascript
// Read a string from another file synchronously
let content;
try {
 content = fs.readFileSync('sync.txt', { encoding: 'utf8' });
} catch(err) {
 // An error occurred
 console.error(err);
}
```

<a href="https://www.buymeacoffee.com/rkycom" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on [LinkedIn](https://www.linkedin.com/in/www-rajeshkumaryadav-com/) and [Twitter](https://twitter.com/rky_com).

{% link https://dev.to/rajeshkumaryadavdotcom/node-js-determining-the-line-count-of-a-text-file-195l %}
{% link https://dev.to/rajeshkumaryadavdotcom/node-js-reading-a-file-line-by-line-5ga9 %}
{% link https://dev.to/rajeshkumaryadavdotcom/node-js-reading-from-a-file-synchronously-28ef %}
{% link https://dev.to/rajeshkumaryadavdotcom/node-js-checking-if-a-file-or-a-directory-exists-1jp6 %}
{% link https://dev.to/rajeshkumaryadavdotcom/node-js-check-permissions-of-a-file-or-directory-3l7k %}
Node.js : Locking modules to specific versions
Tags: node, npm, webdev, javascript
Published: 2021-05-12 03:50:21

By default, `npm` installs the latest available version of modules according to each dependencies' semantic version. This can be problematic if a module author doesn't adhere to semver and introduces breaking changes in a module update, for example.

To lock down each dependencies' version (and the versions of their dependencies, etc) to the specific version installed locally in the `node_modules` folder, use
```
npm shrinkwrap
```
This will then create a `npm-shrinkwrap.json` alongside your `package.json` which lists the specific versions of dependencies

<a href="https://www.buymeacoffee.com/rkycom" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

With all that being said, I highly recommend you keep learning!

Thank you for reading this article. Please feel free to connect with me on [LinkedIn](https://www.linkedin.com/in/www-rajeshkumaryadav-com/) and [Twitter](https://twitter.com/rky_com).
How I built my Blog With Next.js 🌟
Published: 2021-05-12 03:43:52

Post Originally at my [website](https://judetejada.vercel.app/blog/how-i-built-my-blog) 


I decided to revamp my portfolio as there were a lot of things that I wanted to add on such as sub-pages and even dynamically generated pages, while my previous portfolio still gets the job done I figure out it's now the right time to further revamp my portfolio.

When I'm working on a project I like to structure out my process into workflows that help me get an organized roadmap of achieving the project till the end result.


## Research
The first process is to do research, this includes finding inspirations from other people's portfolios and setting the right theme to fit my portfolio website, I also created a mood-board in which I could use as my reference when I'm building out a portfolio. Creating a unique concept takes time and so following what's already been used would help us on focusing on the important matters and will save us time.

## Design
One big mistake that I had while building out my portfolio as I didn't sketch out nor created a wireframe of what my actual website would look like. I straight up got myself into coding and that's where things had gone awry, there were a lot of times that I iterated a particular section and a lot of inconsistencies with my colors, font sizes but either way, it turned out pretty well and I had learned a lesson

>Always start with wireframing your website as it helps you get a clear sense of the idea of what you're trying to build and you won't get end up with multiple revisions which could potentially waste so much of your time.

## Coding the website
This is the most exciting part of revamping my portfolio and it's when I get to choose what tools, technologies that I would plan to use. I had chosen to use Tailwind, Next.js, and MDX. I've been using Next.js in my previous project and I had grown to absolutely enjoy it, it's my go framework for building a project, I use to design my project from scratch with CSS but this time I decided to use Tailwind and explore with it, One of the things that I like about Tailwind is that it doesn't lock you in their design system and instead it lets you be the one to create for yourself.

## Conclusion
After a couple of days building out my portfolio website I had learned a couple of things and also explore new technologies. I'll continue to improve my website as I think there is still a couple of improvements, especially with MDX since I could use JSX component inside of markdown.
Why Programming can be Very Important
Published: 2021-05-12 03:39:54

Do you want to be a programmer? Well, you are in the right place. Programming is one of the most interesting things you can learn in your life. In the future, programming can be very important. Because Elon Musk is developing A.I (Artificial Intelligence) and rocket ships. Again, Programming can be very important because like the Apollo 11 mission, the Nasa Engineers need to program the Eagle to land on the moon correctly. This can also apply to other things as well like: Facebook, Instagram, etc. 

All in all, Programming can be very important.
Rspec-Rails Cheat Sheet
Tags: rails, cheatsheet
Published: 2021-05-12 02:45:27

### Time helpers

```
travel_to Time.new(2014, 11, 14, 01, 04, 44)
...
travel_back

travel_to Time.new(2014, 11, 14, 01, 04, 44) do
  ...
end
```

### Matchers

```rb
be_a_new(Widget)  # new_record?
render_template("new")
render_template(partial: 'form', locals: {...})
redirect_to(widgets_path)
route_to(..)
be_routable
have_http_status(500)
have_http_status(:created)
```

### Features

```rb
# spec/features/*.rb
feature 'Signing in' do
  given(:something) { "hi" }

  background do
    User.make email: 'hi@gmail.com'
  end

  scenario 'Signing in with credentials' do
  end
end
```

### Helpers

```rb
# spec/helpers/*.rb
describe EventsHelper do
  describe "#link_to_event" do
    it "displays the title, and formatted date" do
      event = Event.new("Ruby Kaigi", Date.new(2010, 8, 27))

      # helper is an instance of ActionView::Base configured with the
      # EventsHelper and all of Rails' built-in helpers
      expect(helper.link_to_event).to match /Ruby Kaigi, 27 Aug, 2010/
    end
  end
end
```

### Routing

```rb
# spec/routing/*.rb
describe "routing to profiles" do
  it "routes /profile/:username to profile#show for username" do
    expect(get: "/profiles/jsmith").to route_to(
      controller: "profiles",
      action: "show",
      username: "jsmith"
    )
  end

  it "does not expose a list of profiles" do
    expect(get: "/profiles").not_to be_routable
  end
end
```

### Request

```js
# spec/requests/*.rb
describe "home page" do
  it "displays the user's username after successful login" do
    get "/login"
    post "/login", username: "jdoe", password: "secret"

    expect(response.status).to eql 200
    expect(response).to redirect_to(...)
    expect(response).to render_template(:show)
    expect(response.body).to include 'hello'
    follow_redirect!
  end
end
```

### Controllers

```rb
# spec/controllers/*.rb
describe MyController do
  describe "POST update" do
    render_views #optional

    it "works" do
      post :update, { user: { name: "john" } }

      controller
      controller.send ...

      response
      expect(response).to be_success
      expect(response).to have_http_status(200)
      expect(response).to render_template("index")
      expect(response).to redirect_to '/..'

      expect(assigns :article).to eq article

      response.status
    end
  end
end
```

### Models

```rb
# spec/models/*.rb
describe MyModel do
end
```

### Spec tasks

    rake spec:controllers
    rake spec:helpers
    rake spec:lib
    rake spec:mailers
    rake spec:models
    rake spec:requests
    rake spec:routing
    rake spec:views

### Reference

* [Rspec-Rails Cheat Sheet](https://cheatsheetmaker.com/rspec-rails)
Bolt Cheat Sheet
Published: 2021-05-12 02:43:34

### Also see

* [Bolt Cheat Sheet](https://cheatsheetmaker.com/bolt-quickstart)
* [Cheat Sheet Maker](https://cheatsheetmaker.com)

### Run Bolt

```bash
bolt task run mymodule::myscript -n node1.example.com,node2.example.com --private-key ~/.ssh/id_rsa-private
```

See `bolt task run --help` for more information and command line options.

### Create a module with a task

```bash
mkdir -p ~/.puppetlabs/bolt/modules/mymodule/tasks
cp myscript.sh ~/.puppetlabs/bolt/modules/mymodule/tasks/
```

Tasks can be written in any language your targets can run. See [writing tasks](https://puppet.com/docs/bolt/latest/writing_tasks.html) for more details.

### Install Bolt

```bash
# On MacOS
brew cask install puppetlabs/puppet/puppet-bolt
# On Windows
choco install puppet-bolt
```

Bolt is available as a package for most platforms. See [installing bolt](https://puppet.com/docs/bolt/latest/bolt_installing.html)
Secrets to using REM in CSS: CSS Tips
Tags: css, programming, codenewbie, webdev
Published: 2021-05-12 02:39:07

As device sizes proceed to wander and programs give more client alternatives, utilizing static units simply doesn't cut it any longer. Some such countless individuals set their browser inclination to bigger content with no impact on the sites they visit. 

While pixels will permit clients to zoom in and out, their content settings on their PC or program won't have any impacts. 

By utilizing REM units you make Scalable sites that keep up the proportions between components while likewise scaling to the client's inclination. So if a client sets their settings to have bigger content - your site ought to react so they can appreciate it like every other person!

Over the last couple of years, I have stopped using pixel units and also advising people to do the same. Let's see why you should use REM units. 

---

### REM vs EM

But first, we must clear up the difference between EM and REM units. Both units are calculated to form the font size and use a base value the number of ems/rems is the multiple of that value. 

Example: 

```css
/*Base fontsize 16px*/
1rem = 16px
2rem = 32px

1em = 16px
2em = 32px
```

The difference is that REM values always use the root base value (set on the HTML element), whereas EM units are relative to their container. 

Example: 

```css
/*Base fontsize 16px*/
/*Container fontsize 20px*/

1rem = 16px
2rem = 32px

1em = 20px
2em = 40px
```

### What is the root base value? 

The default base font size is set by the browser and on most of the browser 1 rem = 16px.  This means you can even use the standardized 8px grid since 0.5rem = 8px. 
It is possible to set your base value by changing the `font-size` of the HTML element but the beauty f letting the browser control the default value is that users can change it. 

### Fluid Elements

By using REM units and letting the browser (and user control the base value, you create scalable elements that will keep their form when they are sized up or down. This created truly fluid and flexible layouts that will scale beautifully no matter the users' personal preference and settings. 

Example:- 

```css
h1 {
   font-size: 2rem; 
 }

p {
   font-size: 1rem;
}
```

The title will be always larger than the paragraph text no matter what the base size is. They scale together. And this is the same with the buttons too, `font-size`, `border-radius` and padding all scales with the base size. 

### What about PX units?

The pixel has a place on the web through ad there are plenty of times when you require a fixed value that isn't scald based on the user's preference. For example, pixels are still good for setting borders that don't always need to scale. 

---

Thank you for showing interest and reading. So use REM instead of PX🤗.
Semver Cheat Sheet
Tags: semver, cheatsheet
Published: 2021-05-12 02:37:37

### References

 * <http://semver.org/>
 * <https://docs.npmjs.com/misc/semver>
 * [Semver Cheat Sheet](https://cheatsheetmaker.com/semver)
 * [Cheat Sheet Maker](https://cheatsheetmaker.com)

### Explanation

| `^` | means "compatible with" |
| `~` | means "reasonably close to" |
| `0.x.x` | is for "initial development" |
| `1.x.x` | means public API is defined |

### Pre-releases

    1.2.3-prerelease+build

### Combining ranges

| Range              | Description           |
| ---                | ---                   |
| `>=0.14 <16`       | And (space-separated) |
| `0.14.x || 15.x.x` | Or (pipe-separated)   |

### Hyphenated ranges

| Range              | Description           |
| ---                | ---                   |
| `1.2.3 - 2.3.4`    | is `>=1.2.3 <=2.3.4`  |

#### Partial right

| Range              | Description           |
| ---                | ---                   |
| `1.2.3 - 2.3`      | is `>=1.2.3 <2.4.0`   |
| `1.2.3 - 2`        | is `>=1.2.3 <3.0.0`   |

#### Partial left

| Range              | Description           |
| ---                | ---                   |
| `1.2 - 2.3.0`      | is `1.2.0 - 2.3.0`    |

When the right is partial (eg, `2.3`), missing pieces are assumed to be `x` (eg, `2.3.x`).

When the left is partial (eg, `1.2`), missing pieces are assumed to be `0` (eg, `1.2.0`).

### Ranges

| Range    | Description         | Notes              |
| ---      | ---                 | ---                |
| `~1.2.3` | is `>=1.2.3 <1.3.0` |                    |
| ---      | ---                 | ---                |
| `^1.2.3` | is `>=1.2.3 <2.0.0` |                    |
| `^0.2.3` | is `>=0.2.3 <0.3.0` | (0.x.x is special) |
| `^0.0.1` | is  `=0.0.1`        | (0.0.x is special) |
| ---      | ---                 | ---                |
| `^1.2`   | is `>=1.2.0 <2.0.0` | (like ^1.2.0)      |
| `~1.2`   | is `>=1.2.0 <1.3.0` | (like ~1.2.0)      |
| ---      | ---                 | ---                |
| `^1`     | is `>=1.0.0 <2.0.0` |                    |
| `~1`     | same                |                    |
| `1.x`    | same                |                    |
| `1.*`    | same                |                    |
| `1`      | same                |                    |
| ---      | ---                 | ---                |
| `*`      | any version         |                    |
| `x`      | same                |                    |

### Simple ranges

      1.2.3
     =1.2.3
     >1.2.3
     <1.2.3
    >=1.2.3

Note that suffixed versions (`1.2.3-rc1`) are not matched.

### Semver

Given a version number `MAJOR.MINOR.PATCH`:
{: .-setup}

| `MAJOR` | incompatible API changes                 |
| `MINOR` | add functionality (backwards-compatible) |
| `PATCH` | bug fixes (backwards-compatible)         |
Simple Hook to fetch data (ReactJs)
Tags: react, hooks
Published: 2021-05-12 02:32:00



We will create a simple hook for fetching data from url 
http://jsonplaceholder.typicode.com

We will call http://jsonplaceholder.typicode.com/users and http://jsonplaceholder.typicode.com/posts url

To avoid duplicity of code we will create a useFetch hook and pass a url parameter to it.

```javascript
const useFetch = (url) => {
 ...
};
```

[Watch the video here on my channel](https://youtu.be/zKCVoXo3q5Y)  

### Step 1  : Install axios for fetching data and react-router-dom for routing

```javascript
npm i --save axios  react-router-dom
```

###Step 2 : create useFetch hook for fetching data

```javascript
import {useEffect, useState} from 'react';
import axios from 'axios';

const useFetch = (url) => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  const fetchData = () => {
    axios.get(url).then((res) => {
      setData(res.data);
      setIsLoading(false);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  return {data, isLoading};
};

export default useFetch;
```

###Step 3 : Call the useFetch hook in Users and Posts components

####Users.js

```javascript
import React from 'react';
import useFetch from '../../hooks/useFetch';

const Users = () => {
  let url = 'https://jsonplaceholder.typicode.com/users';
  const {data, isLoading} = useFetch(url);

  return (
    <div className=" container ">
      <div className="card ">
        <div className="card-body">
          {!isLoading && data.map((m, i) => <div key={i}>{m.name}</div>)}
        </div>
      </div>
    </div>
  );
};

export default Users;
```


####Posts.js

```javascript
import React from 'react';
import useFetch from '../../hooks/useFetch';

const Posts = () => {
  let url = 'https://jsonplaceholder.typicode.com/posts/1';
  const {data, isLoading} = useFetch(url);

  return (
    <div>{!isLoading && 'Title : ' + data.title + ' Body : ' + data.body}</div>
  );
};

export default Posts;
```

### Step 4 Configure Route in App.js

####App.js
```javascript
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';

import Users from './components/Users/Users';
import Posts from './components/Users/Posts';

 <Router>
      <Header></Header>
      <Switch>       
        <Route path="/users" component={Users} />
        <Route path="/posts" component={Posts} />       
      </Switch>
    </Router>
```	
###Step 5: Setting up link in Header.js to call the Components

####Header.js
```javascript
import {NavLink} from 'react-router-dom';

<NavLink to="/users" activeClassName="activeClass">
	Users
</NavLink>
<NavLink to="/posts" activeClassName="activeClass">
	Posts
</NavLink>
```


If you had any value adds, don't forget to subscribe [my youtube channel ](https://www.youtube.com/channel/UCajNSAb41SHFYAsCJxUKIMw?sub_confirmation=1)


[Watch the video here on my channel](https://youtu.be/zKCVoXo3q5Y)
Git Log Cheat Sheet
Tags: git, cheatsheet
Published: 2021-05-12 02:30:43

### Also see

- [Git Log Cheat Sheet](https://cheatsheetmaker.com/git-log)
- [Cheat Sheet maker](https://cheatsheetmaker.com)

### Custom formats


```bash
    --pretty="format:%H"
```

### Formatting

```bash
    --abbrev-commit
    --oneline
    --graph
```
### Ordering

```bash
    --date-order
    --author-date-order
    --topo-order              # "smart" ordering
    --reverse
```
### Simplification

```bash
git log -- app/file.rb          # only file
    --simplify-by-decoration    # tags and branches
```
### Limiting

```bash
    --merges
    --no-merges
```

```bash
    --first-parent          # no stuff from merged branches
```

```bash
    --branches="feature/*"
    --tags="v*"
    --remotes="origin"
```
### Search

```bash
    --grep="Merge pull request"   # in commit messages
    -S"console.log"               # in code
    -G"foo.*"                     # in code (regex)
```

```bash
    --invert-grep
    --all-match                   # AND in multi --grep
```
### Basic filters

```bash
-n, --max-count=2
    --skip=2
```

```bash
    --since="1 week ago"
    --until="yesterday"
```

```bash
    --author="Rico"
    --committer="Rico"
```
### Revision ranges

```bash
git log master             # branch
git log origin/master      # branch, remote
git log v1.0.0             # tag

git log master develop

git log v2.0..master       # reachable from *master* but not *v2.0*
git log v2.0...master      # reachable from *master* and *v2.0*, but not both
```

See [gitrevisions](https://cheatsheetmaker.com/git-revisions).
Ubuntu Cheat Sheet
Tags: ubuntu, cheatsheet
Published: 2021-05-12 02:20:14

### Reference

* [Ubuntu Cheat Sheet](https://cheatsheetmaker.com/ubuntu) - [Cheat Sheet Maker](https://cheatsheetmaker.com)

### List services

    service --status-all

### Apt archives path

    /var/cache/apt/archives

### Aptitude stuff

    aptitude search mysql       # Look for something
    dpkg -S `which tsclient`    # What package does it belong to?
    dpkg -L aria2c              # What does this package provide?
    dpkg -i *.deb               # Install a deb file
    dpkg -s nodejs              # Show info

    dpkg --get-selections       # list installed packages