<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Valerie Foster</title>
    <description>The latest articles on DEV Community by Valerie Foster (@fosterv2).</description>
    <link>https://dev.to/fosterv2</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F514156%2F13eb49d9-fdd0-4e44-a3f3-7c6fc95555ce.jpg</url>
      <title>DEV Community: Valerie Foster</title>
      <link>https://dev.to/fosterv2</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fosterv2"/>
    <language>en</language>
    <item>
      <title>Getting Started With Vue.js: Directives Part 2</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Mon, 21 Dec 2020 22:39:49 +0000</pubDate>
      <link>https://dev.to/fosterv2/getting-started-with-vue-js-directives-part-2-49j0</link>
      <guid>https://dev.to/fosterv2/getting-started-with-vue-js-directives-part-2-49j0</guid>
      <description>&lt;p&gt;In my last few blog posts, I’ve been talking about how to get started using Vue.js by giving an introduction to the basic things Vue has to offer. I’ve previously covered the Vue instance, and last week I talked about a few of the Vue directives for handling how things appear on a webpage. I will now talk about the directives that make your Vue app reactive and interactive to a user.&lt;/p&gt;

&lt;p&gt;If you know anything about basic, vanilla JavaScript, you should know that the way to make a webpage reactive is by adding event listeners. There are all different kinds of events, including clicking on an HTML element, scrolling through a page, and pushing keys on the keyboard. The &lt;code&gt;v-on&lt;/code&gt; directive is Vue’s built in way to listen for events. Here’s an example that also uses the &lt;code&gt;v-if&lt;/code&gt; directive, which I covered in my last post:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//  in index.js
new Vue({
  el: '#toggle',
  data: {
    condition: true
  }
})
//  in index.html
&amp;lt;div id="toggle"&amp;gt;
  &amp;lt;button v-on:click="condition = !condition"&amp;gt;Click Me!&amp;lt;/button&amp;gt;
  &amp;lt;p v-if="condition"&amp;gt;Click the Button to toggle me in and out&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, you can see the &lt;code&gt;v-on&lt;/code&gt; directive in action. The part after the colon tells Vue what type of event to listen for; in this case, &lt;em&gt;click&lt;/em&gt;. If I had instead put &lt;em&gt;mouseover&lt;/em&gt;, then it would change every time I moved my cursor over the button. In this example, the &lt;code&gt;v-on&lt;/code&gt; directive points to an action to make the condition variable swap between &lt;em&gt;true&lt;/em&gt; and &lt;em&gt;false&lt;/em&gt;. So with the &lt;code&gt;v-if&lt;/code&gt;, the &lt;strong&gt;p&lt;/strong&gt; element will toggle in and out of the page. I can also have &lt;code&gt;v-on&lt;/code&gt; point to a function in my instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//  in index.js
new Vue({
  el: "#message",
  data: {
    message: "I'm a message!"
  },
  methods: {
    alertMessage: function () {
      alert(this.message)
    }
  }
})
//  in index.html
&amp;lt;div id="message"&amp;gt;
  &amp;lt;button v-on:click="alertMessage"&amp;gt;Click Me!&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example will show an alert at the top of the page with whatever the message variable says, like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--t0xDYIRl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/11kdy0rfhjs5p5n6267z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--t0xDYIRl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/11kdy0rfhjs5p5n6267z.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
There are also all kinds of modifiers for &lt;code&gt;v-on&lt;/code&gt;. Modifiers are “directive postfixes denoted by a dot”. To see a full list of modifiers, you can go to Vue’s documentation on &lt;a href="https://vuejs.org/v2/guide/events.html"&gt;Event Handling&lt;/a&gt;. As an example, there is one modifier for &lt;code&gt;v-on&lt;/code&gt; called &lt;code&gt;.once&lt;/code&gt; that ensures that the event can only be triggered once. So if I add it to the example from earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="counter"&amp;gt;
  &amp;lt;button v-on:click.once="alertMessage"&amp;gt;Click Me!&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The alert will only pop up the first time you click the button. Clicking the button any time afterwards will do nothing.&lt;/p&gt;

&lt;p&gt;Other than &lt;code&gt;v-on&lt;/code&gt;, there is one more directive that lets users interact with the data in your Vue instance. That is &lt;code&gt;v-model&lt;/code&gt;, and it is arguably the most magic of all of the directives Vue gives you. It is magical because it does a lot of work, handles all of the interaction between an &lt;strong&gt;input&lt;/strong&gt;, &lt;strong&gt;textarea&lt;/strong&gt;, or &lt;strong&gt;select&lt;/strong&gt; element, and a variable to associate them with. For a basic example, assuming we have a &lt;code&gt;message&lt;/code&gt; variable with an empty string in our Vue instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="model"&amp;gt;
  &amp;lt;input v-model="message" placeholder="Type something..."&amp;gt;
  &amp;lt;p&amp;gt;You typed: {{ message }}&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just by adding &lt;code&gt;v-model&lt;/code&gt;, this &lt;strong&gt;input&lt;/strong&gt; will always show the current state of the &lt;code&gt;message&lt;/code&gt; variable, any changes to the &lt;strong&gt;input&lt;/strong&gt; will change the &lt;code&gt;message&lt;/code&gt; variable, and any changes to &lt;code&gt;message&lt;/code&gt; will change what appears in the &lt;strong&gt;input&lt;/strong&gt; element.&lt;/p&gt;

&lt;p&gt;There are many different ways to use &lt;code&gt;v-model&lt;/code&gt; depending on what type of &lt;strong&gt;form&lt;/strong&gt; element you are using and how you want to use the variable. When using the &lt;strong&gt;input&lt;/strong&gt; types of &lt;em&gt;checkbox&lt;/em&gt; or &lt;em&gt;radio&lt;/em&gt;, whatever you put as the &lt;em&gt;value&lt;/em&gt; of the &lt;strong&gt;input&lt;/strong&gt; will be stored in the variable from &lt;code&gt;v-model&lt;/code&gt;. Here are some examples:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- The picked variable will change to the string value of
    "Jack" or "Jill" depending on which is selected --&amp;gt;
&amp;lt;input type="radio" id="jack" value="Jack" v-model="picked"&amp;gt;
&amp;lt;label for="jack"&amp;gt;Jack&amp;lt;/label&amp;gt;
&amp;lt;br&amp;gt;
&amp;lt;input type="radio" id="jill" value="Jill" v-model="picked"&amp;gt;
&amp;lt;label for="jill"&amp;gt;Jill&amp;lt;/label&amp;gt;
&amp;lt;p&amp;gt;Picked: {{ picked }}&amp;lt;/p&amp;gt;

&amp;lt;!-- The colors variable is an array of checked colors, because
    you can have more than one checkbox selected at a time --&amp;gt;
&amp;lt;input type="checkbox" id="red" value="Red" v-model="colors"&amp;gt;
&amp;lt;label for="red"&amp;gt;Red&amp;lt;/label&amp;gt;
&amp;lt;input type="checkbox" id="yellow" value="Yellow" v-model="colors"&amp;gt;
&amp;lt;label for="yellow"&amp;gt;Yellow&amp;lt;/label&amp;gt;
&amp;lt;input type="checkbox" id="blue" value="Blue" v-model="colors"&amp;gt;
&amp;lt;label for="blue"&amp;gt;Blue&amp;lt;/label&amp;gt;
&amp;lt;p&amp;gt;Checked colors: {{ colors }}&amp;lt;/p&amp;gt;

&amp;lt;!-- The selected variable will change to whatever string is
    in the option you select --&amp;gt;
&amp;lt;select v-model="selected"&amp;gt;
  &amp;lt;option disabled value=""&amp;gt;Please pick one&amp;lt;/option&amp;gt;
  &amp;lt;option&amp;gt;Lion&amp;lt;/option&amp;gt;
  &amp;lt;option&amp;gt;Tiger&amp;lt;/option&amp;gt;
  &amp;lt;option&amp;gt;Bear&amp;lt;/option&amp;gt;
&amp;lt;/select&amp;gt;
&amp;lt;p&amp;gt;You picked: {{ selected }}&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see from these examples that &lt;code&gt;v-model&lt;/code&gt; can be used in a lot of different ways. But this is just the tip of the iceberg, and you can checkout Vue’s documentation about &lt;a href="https://vuejs.org/v2/guide/forms.html"&gt;Form Inputs&lt;/a&gt; to find out more.&lt;/p&gt;

&lt;p&gt;With this I have finished going over all the main directives that Vue.js gives you. Using these, you can make a webpage interactive and interesting to a user relatively easily because Vue does all the hard work for you, by hooking up your data to elements on the page. So far, I’ve gone over how to do things on a small scale, like having one element on a page react a certain way. But this doesn’t really work well to scale up for large applications. That’s where Vue Components come in. I’ll go over what they are and how to use them another time.&lt;/p&gt;

</description>
      <category>vue</category>
    </item>
    <item>
      <title>Getting Started With Vue.js: Directives</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Wed, 16 Dec 2020 01:46:00 +0000</pubDate>
      <link>https://dev.to/fosterv2/getting-started-with-vue-js-directives-4ocf</link>
      <guid>https://dev.to/fosterv2/getting-started-with-vue-js-directives-4ocf</guid>
      <description>&lt;p&gt;Continuing on from my last two blog posts, I’ll be talking more about some of the basics of Vue.js. I have covered how to start a project using Vue and some of the ways you can use the Vue instance in a project. In this post, I’ll go over Vue’s &lt;em&gt;directives&lt;/em&gt;; the way to make your webpages interactive with the data in your Vue instances.&lt;/p&gt;

&lt;p&gt;Directives are special attributes provided by Vue. They are prefixed with &lt;code&gt;v-&lt;/code&gt; and each one applies specific reactive behavior to the HTML element you add it to on the page. The main Vue directives are &lt;code&gt;v-bind&lt;/code&gt;, &lt;code&gt;v-if&lt;/code&gt;, &lt;code&gt;v-for&lt;/code&gt;, and &lt;code&gt;v-on&lt;/code&gt;. An example using &lt;code&gt;v-bind&lt;/code&gt; looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div v-bind:id="someVariable"&amp;gt;&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;v-bind&lt;/code&gt; attribute is used to access Vue instance variables from inside an HTML attribute. The example above shows the &lt;code&gt;v-bind&lt;/code&gt; attribute being used to assign the &lt;em&gt;id&lt;/em&gt; of the &lt;em&gt;div&lt;/em&gt; to a variable called &lt;code&gt;someVariable&lt;/code&gt;. Unlike referencing a variable in between HTML elements, you cannot use double curly braces to interpret variables in HTML attributes, you have to use &lt;code&gt;v-bind&lt;/code&gt; instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Doesn't work, causes an error! --&amp;gt;
&amp;lt;a href={{ url }}&amp;gt;Vue.js&amp;lt;/a&amp;gt;
&amp;lt;!-- This is the correct way to assign the href attribute to url --&amp;gt;
&amp;lt;a v-bind:href="url"&amp;gt;Vue.js&amp;lt;/a&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use &lt;code&gt;v-bind&lt;/code&gt; to assign any attribute an element might have to a variable. But &lt;code&gt;v-bind&lt;/code&gt; can get more confusing when you need to attach more than one variable to an attribute. When adding styling to a page, the &lt;em&gt;class&lt;/em&gt; and &lt;em&gt;style&lt;/em&gt; attributes might need to have many variables associated with them. In that case, you can use array or object syntax with &lt;code&gt;v-bind&lt;/code&gt;, like these examples with multiple classes on each element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div v-bind:class="[activeClass, errorClass]"&amp;gt;
  &amp;lt;!-- This will have the class names of whatever is in
    the 'activeClass' and 'errorClass' variables --&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div v-bind:class="{ active: isActive, 'text-danger': hasError }" &amp;gt;
  &amp;lt;!-- This will have the classes of 'active' and 'text-danger'
    depending on if their variables are true or false --&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When using the style attribute, it’s often better to create a style object in the instance to bind to the attribute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in index.html
&amp;lt;div v-bind:style="styleObject"&amp;gt;
  &amp;lt;!-- content --&amp;gt;
&amp;lt;/div&amp;gt;
// in index.js
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way, if your style object gets too big, it’s not taking up space in your HTML.&lt;/p&gt;

&lt;p&gt;The next directive uses a concept that should be very familiar to any programmer. The &lt;code&gt;v-if&lt;/code&gt; directive is used for conditional rendering, and it evaluates the condition it is given the same way as an if-statement does in code. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="if-directive"&amp;gt;
  &amp;lt;h1 v-if="condition"&amp;gt;I'm conditionally rendered!&amp;lt;/h1&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;condition&lt;/code&gt; that &lt;code&gt;v-if&lt;/code&gt; points to should be some data that you have defined that can be evaluated to &lt;em&gt;true&lt;/em&gt; or &lt;em&gt;false&lt;/em&gt;. Now, if the &lt;code&gt;condition&lt;/code&gt; is &lt;em&gt;true&lt;/em&gt;, you will see the &lt;code&gt;h1&lt;/code&gt; tag on the webpage, and if it is &lt;em&gt;false&lt;/em&gt;, this will be an empty &lt;code&gt;div&lt;/code&gt;. You can test this out by creating a Vue instance attached to this &lt;code&gt;div&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let ifDirective = new Vue({
  el: "#if-directive",
  data: {
    condition: true
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if you have the page open in your browser, you should see the &lt;code&gt;h1&lt;/code&gt; tag, but if you open the console and set &lt;code&gt;ifDirective.condition&lt;/code&gt; to &lt;em&gt;false&lt;/em&gt;, you can see the header disappear.&lt;/p&gt;

&lt;p&gt;Just like if-statements with any programming language, &lt;code&gt;v-if&lt;/code&gt; also has the associated &lt;code&gt;v-else&lt;/code&gt; and &lt;code&gt;v-else-if&lt;/code&gt; so you can give other options for what to render depending on a variety if conditions, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="gender"&amp;gt;
  &amp;lt;p v-if="person.gender === 'M'"&amp;gt;
    Male
  &amp;lt;/p&amp;gt;
  &amp;lt;p v-else-if="person.gender === 'F'"&amp;gt;
    Female
  &amp;lt;/p&amp;gt;
  &amp;lt;p v-else&amp;gt;
    Other
  &amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the last directive I’ll talk about in this post is &lt;code&gt;v-for&lt;/code&gt;. This should also sound familiar to any programmer, and as you might expect, the &lt;code&gt;v-for&lt;/code&gt; attribute is designed to loop over a collection or list. Here’s an example of what a Vue instance with a list could look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const forDirective = new Vue({
  el: "#for-directive",
  data: {
    todos: [
      { text: 'Wash dishes', isComplete: false },
      { text: 'Do laundry', isComplete: true },
      { text: 'Check email', isComplete: false }
    ]
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the HTML would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ul id="for-directive"&amp;gt;
  &amp;lt;li v-for="todo in todos"&amp;gt;
    {{ todo.text }}
  &amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sGBLY-UI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/jvh0cubauaerj1d98ufn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sGBLY-UI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/jvh0cubauaerj1d98ufn.png" alt="Todo List"&gt;&lt;/a&gt; This will render a list like the one above. If you have the &lt;em&gt;index.html&lt;/em&gt; page open in your browser and you open the console, you can add or remove items in the &lt;code&gt;todos&lt;/code&gt; array and see the list update on the page. The list will always update whenever there is a change to the list in your instance. The &lt;code&gt;v-for&lt;/code&gt; attribute also gives you the ability to loop over an object, and a way to access the index and/or key of each of the elements in the collection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Using the index of each item in the array
v-for="(item, index) in items"
// Looping over an object
v-for="value in object"
// Looping over an object with it's key names and index values
v-for="(value, name, index) in object"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One thing to note is that it is not advised to use &lt;code&gt;v-if&lt;/code&gt; with &lt;code&gt;v-for&lt;/code&gt;. The main reason to try to use them together is when you only want to display items in the list that fit a condition. But the better way to do this is to use a computed property. You should use computed properties to display a sorted or filtered part of your original list. If we use the example from earlier with the todo list, we could add a computed property to the instance that filters the list by items that are not completed, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;computed: {
  completedTodos: function () {
    return this.todos.filter(function (todo) {
      return !todo.isComplete
    })
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then you can use &lt;code&gt;v-for&lt;/code&gt; with this computed property to only display the todos that are not completed to the page:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;li v-for="todo in completedTodos"&amp;gt;
  {{ todo.text }}
&amp;lt;/li&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another thing to note about the &lt;code&gt;v-for&lt;/code&gt; directive is that you should give each element in the list a unique key attribute. This is so that Vue can properly keep track of each element’s identity so it will reuse existing elements, instead of recreating them when there is a change to the collection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div v-for="item in items" v-bind:key="item.id"&amp;gt;
  &amp;lt;!-- content --&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, with everything I have talked about in my blog posts on Vue, I have covered most of the different ways to display data from your Vue instances to a webpage. And because of the the way Vue is set up, the page will change according to any updates that are made to the data. But I still haven’t really covered how to allow a user to interact with your webpage. That requires the use of the &lt;code&gt;v-on&lt;/code&gt; directive, and I’ll spend time talking about that in my next blog post.&lt;/p&gt;

</description>
      <category>vue</category>
    </item>
    <item>
      <title>Getting Started With Vue.js: The Vue Instance</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Mon, 14 Dec 2020 20:05:18 +0000</pubDate>
      <link>https://dev.to/fosterv2/getting-started-with-vue-js-the-vue-instance-162e</link>
      <guid>https://dev.to/fosterv2/getting-started-with-vue-js-the-vue-instance-162e</guid>
      <description>&lt;p&gt;In my last blog post, I gave an introduction of how to get started learning Vue. I talked about how it is similar to React, the framework I’ve used most often, and I gave some instructions for one of the ways to get a project set-up to try out Vue on your own computer. I ended my post by talking about the Vue instance and how to show data from it on a webpage. The instance is what Vue is all about, and I’ll go into some of the things it can do and how to use it in this blog post.&lt;/p&gt;

&lt;p&gt;As a reminder from last time, a basic Vue instance looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Vue({
  data: {
    // put properties you will use here
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;data&lt;/code&gt; part of the Vue instance is arguably the most important. Any properties that you put into the data object are automatically tracked by Vue, and any changes you make to any of these properties will cause a re-render to your page so it will always show the updated values. Any sort of data that you want to use and keep track of should go in here. The data you keep in your &lt;code&gt;data&lt;/code&gt; object can be of most any type; numbers, a String, a boolean value (&lt;em&gt;true&lt;/em&gt; or &lt;em&gt;false&lt;/em&gt;), an array, or even a function. It can also be something evaluated like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Vue({
  data: {
    date: new Date().toLocaleString()
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example uses JavaScript’s built in Date class to get the exact date and time when it is called, then uses a method to turn the date object into a human readable String. As another refresher, the way to use this property in a webpage is by wrapping it in double brackets in your HTML and adding the &lt;code&gt;el&lt;/code&gt; property to the instance with a reference to the HTML element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="name"&amp;gt;
  {{ date }}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can see the &lt;code&gt;date&lt;/code&gt; String with the date and time on the page like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OTsia7ik--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/75w8p9r1eet2dy8qlj8j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OTsia7ik--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/75w8p9r1eet2dy8qlj8j.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
This date will be the exact date and time from when you loaded the page, and it will not update unless you refresh the page. When interpolating data inside these double brackets, you are not just limited to referencing a predefined piece of data, you can also use a piece of code to change what shows up on the page. For example, if you wanted to only show the date without the time, you could split the &lt;code&gt;date&lt;/code&gt; property at the comma and only display the first part, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{{ date.split(',')[0] }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One thing to note: you can only put one expression in each of the pairs of brackets, so you can’t do anything too complicated to the data in your HTML. But there are things you can add to your Vue instance to write longer or more complicated code.&lt;/p&gt;

&lt;p&gt;Another property you can add to the Vue instance besides &lt;code&gt;el&lt;/code&gt; and &lt;code&gt;data&lt;/code&gt; is &lt;code&gt;methods&lt;/code&gt;. Up till now, I’ve only talked about opening the console to manually change the data in your instance, but you’ll often want to use functions to do this. Here’s an example of an instance with the &lt;code&gt;method&lt;/code&gt; property:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Vue({
  el: "#counter",
  data: {
    count: 0
  },
  methods: {
    add: function () {
      this.count++
    }
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, using a directive, something I’ll talk more about in my next blog post, you can attach this function to a button on the DOM:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="counter"&amp;gt;
  &amp;lt;p&amp;gt;Count: {{ count }}&amp;lt;/p&amp;gt;
  &amp;lt;button v-on:click="add"&amp;gt;Add&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This example uses the &lt;code&gt;v-on&lt;/code&gt; directive to create an event listener when you click the button, and it attaches the &lt;code&gt;add&lt;/code&gt; function to the listener. Now, if you click the Add button you can see the &lt;code&gt;count&lt;/code&gt; go up on the screen.&lt;/p&gt;

&lt;p&gt;The last property for Vue instances that I’ll talk about is the &lt;code&gt;computed&lt;/code&gt; property. It is very similar to the &lt;code&gt;methods&lt;/code&gt; property, in that it also uses functions. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new Vue({
  data: {
    firstName: "Jane",
    lastName: "Doe"
  },
  computed: {
    fullName: function () {
      return `${this.firstName} ${this.lastName}`
    }
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This computed property will always return the &lt;code&gt;firstName&lt;/code&gt; and &lt;code&gt;lastName&lt;/code&gt; properties with a space between, and it will update whenever one of the other properties changes. You might think it would be the same thing to have this function in the &lt;code&gt;methods&lt;/code&gt; property or to make this function a part of &lt;code&gt;data&lt;/code&gt;, but it is slightly different. For one thing, if you use a computed property, you can reference it in the DOM the same as you would any piece of data, instead of using parentheses to call it like a function. Also, a computed property only updates when some of the data it uses updates, as opposed to functions that re-compute the result any time it’s referenced in the DOM. So, if you are doing a complicated and time consuming evaluation, it will be more expensive time-wise not to use a computed property.&lt;/p&gt;

&lt;p&gt;Ultimately, Vue instances are designed to help you reference and change data on your webpages by making it easy to keep track of updates and giving you a variety of ways to change the data in any way you might need. So far, I’ve only talked a little about all the cool ways Vue gives you to render that data to the DOM. That will be the focus of my next blog post, where I’ll talk about Vue directives.&lt;/p&gt;

</description>
      <category>vue</category>
    </item>
    <item>
      <title>Getting Started With Vue.js</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Tue, 08 Dec 2020 02:31:48 +0000</pubDate>
      <link>https://dev.to/fosterv2/getting-started-with-vue-js-kc6</link>
      <guid>https://dev.to/fosterv2/getting-started-with-vue-js-kc6</guid>
      <description>&lt;p&gt;Designing things for the web nowadays requires that sites be interactive and react quickly. There have been many studies done about how users are likely to leave a site if it takes too long to load and update. That is where frontend software development comes in. And the most popular coding language to make a website immediately responsive is JavaScript. Because JavaScript has become so popular, there are now a large number of frameworks that make it easy to make your website interactive. Arguably the most popular one is React.js, and this is what I was taught to use in my bootcamp. But I decided it would be good to learn another one, at the very least to see what it is like to teach myself how to use a framework. So I decided to look into &lt;a href="https://vuejs.org/"&gt;Vue.js&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;One thing I’d heard is that, since I know React, learning another framework isn’t as hard, since they all have similar concepts. From what I’ve seen, that is mostly true. Both React and Vue have a way to keep track of some sort of “state” that affects what is displayed on a webpage. Using this state, both React and Vue have ways to add things to html so you can cycle through a list and have html elements show up on the page for each thing in the list. They both have ways to make something only show up on a webpage depending on a condition. And they both have ways to make certain elements react to the events you specify.&lt;/p&gt;

&lt;p&gt;In comparison to React, it is very easy to get started with adding Vue to a project, you just need to add the script that Vue provides in their guide to your HTML file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"&amp;gt;
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another comparison is that, in React, everything is written in JSX, which is a syntax extension to JavaScript that was created to be used with React. I personally like JSX, but it may be hard for some people to get a handle on, so Vue is better for beginners in this way as well. Vue doesn’t have its own syntax, it just uses HTML and JavaScript.&lt;/p&gt;

&lt;p&gt;I taught myself about Vue through the &lt;a href="https://vuejs.org/v2/guide/"&gt;guide&lt;/a&gt; they have on their website. Similar to React’s create-react-app, they have a way to scaffold a new project with all the structure you need for a full project with &lt;a href="https://cli.vuejs.org/"&gt;vue-cli&lt;/a&gt;. But to start out with learning Vue’s, I decided to test all of the concepts out using a very basic project with a simple structure. It just has three files: &lt;em&gt;index.html&lt;/em&gt;, &lt;em&gt;index.js&lt;/em&gt;, and &lt;em&gt;index.css&lt;/em&gt; (the css file isn’t necessary, I just added it so I can style some things). The &lt;em&gt;index.html&lt;/em&gt; file looks something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
   &amp;lt;html&amp;gt;
     &amp;lt;head&amp;gt;
       &amp;lt;link rel="stylesheet" href="index.css"&amp;gt;
       &lt;b&gt;&amp;lt;script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"&amp;gt;
       &amp;lt;/script&amp;gt;&lt;/b&gt;
     &amp;lt;/head&amp;gt;
     &amp;lt;body&amp;gt;
       . . .    
     &amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
     &amp;lt;/body&amp;gt;
   &amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You could also put all of your JavaScript in the &lt;code&gt;script&lt;/code&gt; tag at the bottom of the &lt;code&gt;body&lt;/code&gt; tag in your HTML file instead of linking the &lt;em&gt;index.js&lt;/em&gt; file in, but I think this makes the HTML file to long and involved so I prefer to put all of the JavaScript in a separate &lt;em&gt;index.js&lt;/em&gt; file. To see the &lt;em&gt;index.html&lt;/em&gt; file in my browser, I just run this command in my terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ♥ &amp;gt; open index.html
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The main thing you need to get started using Vue is the Vue instance. A basic example, using the classic “Hello, World!”, would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var hello = new Vue({
  el: '#hello',
  data: {
    message: 'Hello, World!'
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;data&lt;/code&gt; part of a Vue instance is an object with keys and values with data you want to use, and Vue will keep track of it as it changes. In a Vue instance, you can access anything in the data object directly from the instance, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;hello.message  // =&amp;gt; "Hello, World!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You use &lt;code&gt;el&lt;/code&gt; to attach the instance to an HTML element, in this case something with an &lt;em&gt;id&lt;/em&gt; of &lt;em&gt;hello&lt;/em&gt;. This way, inside the HTML element you can just use &lt;code&gt;message&lt;/code&gt; directly to reference it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="hello"&amp;gt;
  {{ message }}
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The double brackets are the way we link the data from the Vue instance to the DOM, so if you open the console and change &lt;code&gt;hello.message&lt;/code&gt; to equal something else, you will immediately see the page update to include the new value.&lt;/p&gt;

&lt;p&gt;But just being able to show some data from a Vue instance on the screen, and only being able to change it though the console isn’t very interesting. Vue gets a lot more useful when you start adding &lt;em&gt;directives&lt;/em&gt; and add functions so you can interact with the data that appears on the screen. I’ll go into the basics of what Vue directives are, some of the ones that are available in Vue, and how to use them in my next blog post.&lt;/p&gt;

</description>
      <category>vue</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
    <item>
      <title>Intro To JavaScript Testing With Mocha: Part 2</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Wed, 02 Dec 2020 19:13:53 +0000</pubDate>
      <link>https://dev.to/fosterv2/intro-to-javascript-testing-with-mocha-part-2-o6n</link>
      <guid>https://dev.to/fosterv2/intro-to-javascript-testing-with-mocha-part-2-o6n</guid>
      <description>&lt;p&gt;In my last blog post I talked about how to get started with writing tests for a JavaScript project using the &lt;a href="https://mochajs.org/"&gt;Mocha&lt;/a&gt; testing library. As I mentioned at the end of that post, this time I will talk about some of the more interesting and less intuitive things you can do when testing with Mocha.&lt;/p&gt;

&lt;p&gt;One interesting thing that Mocha gives you is the hooks &lt;code&gt;before()&lt;/code&gt;, &lt;code&gt;after()&lt;/code&gt;, &lt;code&gt;beforeEach()&lt;/code&gt;, and &lt;code&gt;afterEach()&lt;/code&gt;. You can use these inside a &lt;code&gt;describe&lt;/code&gt; block, and each of them has a different purpose: &lt;code&gt;before&lt;/code&gt; and &lt;code&gt;after&lt;/code&gt; are only run once, before or after all of your tests in &lt;code&gt;describe&lt;/code&gt;, while &lt;code&gt;beforeEach&lt;/code&gt; and &lt;code&gt;afterEach&lt;/code&gt; are run before or after each test. One way this can come in handy is if you want to run all of your tests on the same piece(s) of data, like an array. You could define an array at the top level of the &lt;code&gt;describe&lt;/code&gt; block, but if your tests do a lot of transformations to the array, you could use the &lt;code&gt;beforeEach&lt;/code&gt; method to reset the array before each new test like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe('Array', function () {
  let a

  beforeEach(function () {
    a = ["reset", "the", "array", "to", "be", "the", "same"]
  })

  // all of your tests go here
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each hook takes a callback function and an optional description string, the same as the &lt;code&gt;it&lt;/code&gt; function. It also doesn’t matter what order you put your hooks or tests in, the hooks will still be run at the time they are intended, and your tests will run in the order you have written them in your file.&lt;/p&gt;

&lt;p&gt;Another useful thing that Mocha gives you is the ability to write tests that don’t run. This may sound silly, but it can be very helpful. Tests that don’t run are called pending tests and there are a few ways to write them. One way is making a test without a callback. The idea of this type of test is that someone should write a test case for it eventually. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe('Array', function () {
  describe('#includes()', function () {
    // pending test below
    it('should return false when the value is not present')
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pending tests will be included in the test results, and marked as pending. A pending test is not considered as passing or failing. When you run your tests, the result will tell you how many pending tests you have, along with the passing and failing ones. The result would look something like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gkfZXPKI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/t9ix0gh5r7vw1xh7o4ry.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gkfZXPKI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/t9ix0gh5r7vw1xh7o4ry.png" alt="A Nyan Cat version of passing and pending tests"&gt;&lt;/a&gt;&lt;br&gt;
Another way that you can make pending tests is by writing tests that are skipped. One reason you would do this is if you wrote out a test, but it doesn’t pass and you don’t know why, or you don’t want to take the time to fix it right now, then you can skip it temporarily. This is better than commenting out the test because, if it you get a pending result every time you run your tests, you won’t forget to come back to it later. Skipped tests work by appending &lt;code&gt;.skip()&lt;/code&gt; to the test functions. A single skipped test will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe('#includes()', function () {
  it.skip('should return true when present', function () {
    // this test will not be run
  })

  it('should return false when not present', function () {
    // this test will be run
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or, to skip an entire suite, you can use the &lt;code&gt;skip&lt;/code&gt; keyword on the &lt;code&gt;describe&lt;/code&gt; function like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe.skip('#includes()', function () {
  it('should return true when present', function () {
    // this test will not be run
  })

  it('should return false when not present', function () {
    // neither will this one
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last place you could use &lt;code&gt;skip&lt;/code&gt; is inside your test function to skip the test at runtime using &lt;code&gt;this.skip()&lt;/code&gt;. If a test requires an environment or configuration that you wouldn’t be able to know about beforehand, using &lt;code&gt;skip&lt;/code&gt; at runtime is the best way to handle the problem. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;it('should only test in the correct environment', function() {
  if (/* check test environment */) {
    // make assertions
  } else {
    this.skip()
  }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the environment isn’t right, the result of this test will be pending, and it will essentially abort the test, instead of completely skipping it. The example above is also a best practice, compared to leaving the space in the &lt;code&gt;else&lt;/code&gt; block blank, because a blank test will be reported as passing, and it would be much more useful for us to know the test was aborted.&lt;/p&gt;

&lt;p&gt;Opposite but similar to &lt;code&gt;skip&lt;/code&gt;, you can also append &lt;code&gt;.only()&lt;/code&gt; to &lt;code&gt;it&lt;/code&gt; or &lt;code&gt;describe&lt;/code&gt; to choose to run only one distinct test or test suite. This can be useful if you are working to make one specific test pass and you don’t want to waste time waiting while all the other tests are run. Both &lt;code&gt;only&lt;/code&gt; and &lt;code&gt;skip&lt;/code&gt; can be added to any number of tests you like (but adding them to too many would defeat the purpose). One thing to note: any Hooks you have will still be run.&lt;/p&gt;

&lt;p&gt;One other thing that is necessary to consider when writing anything in JavaScript is how to deal with asynchronous code. Mocha has a few ways to deal with asynchronous code in your tests. One way is by adding an argument to the test callback, usually called &lt;code&gt;done&lt;/code&gt;. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;describe('Tea', function () {
  describe('#save()', function () {
    it('should save without error', function (done) {
      let tea = new Tea('Chai')
      tea.save(done)
    })
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;done&lt;/code&gt; like this will ensure that Mocha knows it should wait for this function to be called to complete the test. This format will also handle any errors in the &lt;code&gt;save&lt;/code&gt; function. But if the APIs you are testing return promises instead of taking callbacks, rather than using the &lt;code&gt;done()&lt;/code&gt; callback, you can use &lt;a href="https://www.npmjs.com/package/chai-as-promised"&gt;Chai as Promised&lt;/a&gt;, and have something like this in your test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return expect(Promise.resolve({ foo: "bar" }))
                               .to.eventually.have.property("foo")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The essential piece that Chai as Promised gives you is the &lt;code&gt;eventually&lt;/code&gt; property. It also gives you more than the &lt;code&gt;.have.property()&lt;/code&gt; chains, so you can check for a variety of things. There are more examples of how to use it in their documentation.&lt;/p&gt;

&lt;p&gt;The last thing I will mention is that Mocha has a wide variety of optional flags you can add to the end of your command to run your tests. The flags are all listed in their &lt;a href="https://mochajs.org/#command-line-usage"&gt;documentation&lt;/a&gt;, but I’ll mention a few here. One is &lt;code&gt;--bail&lt;/code&gt;, and it causes the test suite to abort after the first failed test, which is handy if you want to work on fixing one test at a time. There is also the &lt;code&gt;--parallel&lt;/code&gt; flag, which will cause the tests to be run in parallel mode. This mode is designed to help your test suite run faster by making your tests run somewhat at the same time, instead of one after another, which can be very practical and save time if you have a large number of tests to run. There are a few drawbacks to parallel mode though, so make sure you know enough about parallel mode to recognize if it will work for you.&lt;/p&gt;

&lt;p&gt;And this is the end of my introduction to testing with Mocha. There are other JavaScript testing libraries, but Mocha is one that is well used, thoroughly documented, and, as I hope you can tell from my posts, easy enough to work with. Tests are very useful, and I hope my posts have convinced you to consider using Mocha to write tests for your next JavaScript project.&lt;/p&gt;

</description>
      <category>testing</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Intro to JavaScript Testing With Mocha</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Wed, 02 Dec 2020 19:06:09 +0000</pubDate>
      <link>https://dev.to/fosterv2/intro-to-javascript-testing-with-mocha-4g59</link>
      <guid>https://dev.to/fosterv2/intro-to-javascript-testing-with-mocha-4g59</guid>
      <description>&lt;p&gt;With my last few blog posts, I spent time talking about the importance of testing with software development, and I gave an intro to writing tests with Rails. For this post, I’m going to talk about how to write tests in one of the foremost JavaScript testing frameworks.&lt;/p&gt;

&lt;p&gt;With plain old vanilla JavaScript, not using any frameworks like React or Angular, there are a variety of testing frameworks you can choose from, but I am going to talk about &lt;a href="https://mochajs.org"&gt;Mocha&lt;/a&gt;. The reason I chose Mocha is that the syntax is similar to the tests I was writing with Rails, and it is the framework my Bootcamp used for writing tests, so it feels familiar to me. It also has very good documentation with clear examples and explanations, and it has been around for a long time so they’ve had a chance to iron out all the bugs, and there are a lot examples of it being used.&lt;/p&gt;

&lt;p&gt;To get started with using Mocha for your JavaScript project, run these commands in the top level of your project directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; npm install mocha
~ // ♥ &amp;gt; mkdir test
~ // ♥ &amp;gt; touch test/test.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These commands will add Mocha to your project, create a test directory, and make a file to write your tests in. The test file doesn’t have to be called &lt;code&gt;test.js&lt;/code&gt;, you can name it whatever you like, and if you’re going to be testing multiple files, you should have a test file for each one with a name referencing the file you’re testing, like &lt;code&gt;&amp;lt;filename&amp;gt;Test.js&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now for writing you first test. Using Node.js’ built-in &lt;a href="https://nodejs.org/api/assert.html"&gt;assert&lt;/a&gt; module, you could write a simple test like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const assert = require('assert') // from Node.js' assert module

describe('Array', function () {
  describe('#indexOf()', function () {
    it('should return -1 when the value is not present', function(){
      assert.equal([1, 2, 3].indexOf(4), -1)
    })
    it('should return the index when present', function(){
      assert.equal([1, 2, 3].indexOf(2), 1)
    })
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is pretty clear from the function names what is going on here. The &lt;code&gt;describe&lt;/code&gt; function is given a name that tells you what all of the tests inside it are going to be testing; in this example JavaScript’s &lt;code&gt;Array&lt;/code&gt; &lt;code&gt;indexOf&lt;/code&gt; function. The &lt;code&gt;it&lt;/code&gt; function is given a name that describes exactly what the test is checking for, as well as a callback function. Inside the callback is an assertion. Assertions are designed to evaluate something for expected results. In this example we check that each call of the &lt;code&gt;indexOf&lt;/code&gt; function on the given array returns the number we expect.&lt;/p&gt;

&lt;p&gt;Now to run the tests from the command line, and see the results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; ./node_modules/mocha/bin/mocha

  Array
    #indexOf()
      ✓ should return -1 when the value is not present
      ✓ should return the index when present

  2 passing (7ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One thing to note here: you can see from the result that tests were run in the order that they were written in the file. This will always be the case for all tests that are written to run normally (I’ll get into running tests “abnormally” another time).&lt;/p&gt;

&lt;p&gt;Back to running the tests, you can see that the command to run them is long and annoying to type out, so to make it easier you can set up a test script in your package.json file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
  "test": "mocha"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then you can run your tests with a simple command (you use &lt;code&gt;test&lt;/code&gt; because it is the key you put in your script):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; npm test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another thing you can add to your &lt;code&gt;script&lt;/code&gt; for running your tests is a reporter. Reporters change the way the results of your tests look in your terminal. The example I have above uses &lt;code&gt;spec&lt;/code&gt;, which is the default. There is a wide range of reporters, some with the function descriptions for passing tests included, like &lt;code&gt;span&lt;/code&gt;, and some that just include the name of the function if it fails. There is a full list of the reporters Mocha has &lt;a href="https://mochajs.org/#reporters"&gt;here&lt;/a&gt;. My favorite is &lt;code&gt;nyan&lt;/code&gt; and it looks like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HSY2lQIS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/j6yjt1or9oiqn11y41md.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HSY2lQIS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/j6yjt1or9oiqn11y41md.png" alt="A Nyan Cat version of passing tests"&gt;&lt;/a&gt;&lt;br&gt;
To change your reporter to something other than &lt;code&gt;span&lt;/code&gt; you just have to change the script in your package.json to look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
  "test": "mocha --reporter &amp;lt;reporter-name&amp;gt;"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The example I have above works just fine, but there are other options for how to write tests. For example, Mocha allows you to use any assertion library you want. One that I like because it has very useful and clear types of assertions is called &lt;a href="https://www.chaijs.com/"&gt;chai&lt;/a&gt;; it has &lt;code&gt;expect()&lt;/code&gt;, &lt;code&gt;assert()&lt;/code&gt; and &lt;code&gt;should&lt;/code&gt;-style assertions, and you can choose to use any of these you like. After installing chai with &lt;code&gt;npm install chai&lt;/code&gt;, I could rewrite the tests from before to look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const expect = require('chai').expect; // add to the top of the file

describe('Array', function () {
  describe('#indexOf()', function () {
    it('should return -1 when the value is not present', function(){
      expect([1, 2, 3].indexOf(4)).to.equal(-1)
    })
    it('should return the index when present', function(){
      expect([1, 2, 3].indexOf(2)).to.equal(1)
    })
  })
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I personally like this better because I think &lt;code&gt;expect(a).to.equal(b)&lt;/code&gt; makes it clearer to someone reading it what you’re checking for, as opposed to &lt;code&gt;assert.equal(a, b)&lt;/code&gt;. There are also a lot more methods than just &lt;code&gt;equal()&lt;/code&gt; that you can use in your assertions, for example, &lt;code&gt;expect(foo).to.be.a(‘string’)&lt;/code&gt;. You can see all of them listed out in chai’s documentation.&lt;/p&gt;

&lt;p&gt;Another thing to note: Passing arrow functions to Mocha is discouraged. Arrow functions bind this so you cannot access the Mocha context. This can sometimes lead to some errors in your tests, and while arrow functions will usually work, avoiding them will cause you less problems down the line.&lt;/p&gt;

&lt;p&gt;And that is all I’m going to talk about in writing JavaScript tests with Mocha today. I think I’ve laid a good foundation for how to get started with writing tests for a basic JavaScript project. In my next post, I’ll go into some of the more interesting things that you can do with Mocha tests.&lt;/p&gt;

</description>
      <category>testing</category>
      <category>javascript</category>
      <category>mocha</category>
    </item>
    <item>
      <title>Intro to Testing with Rails: Controller Tests</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Tue, 24 Nov 2020 01:21:10 +0000</pubDate>
      <link>https://dev.to/fosterv2/intro-to-testing-with-rails-controller-tests-502b</link>
      <guid>https://dev.to/fosterv2/intro-to-testing-with-rails-controller-tests-502b</guid>
      <description>&lt;p&gt;This is the final part in my series of posts about testing with Rails. Previously, I talked about getting started with Rails testing, and I talked about writing tests for the Model and View parts of the MVC pattern. This post will talk about how to write tests for the Controller part of the MVC framework, testing your routes and controller actions. This is the last important piece of testing your Rails application.&lt;/p&gt;

&lt;p&gt;Testing can open up a whole new way to think about developing code. One way to think about development is using something called Test Driven Development, or TDD. TDD is a software development process where you write a test with the desired behavior you want your application to have, then you write the code to make the test pass. This way of developing code can be very efficient. For one thing, it forces you to think about what functionality you want to add and exactly what result you want it to have. This also makes sure you don’t have any pieces of untested code — if you write your tests after the fact, you could forget to check the functionality for some sections of code.&lt;/p&gt;

&lt;p&gt;Also, TDD can make it easier to figure out why your tests are failing. When you write functionality to pass the test you just wrote, you have a better idea of what sections of code come into play in making your test pass. Therefore, if the test is still failing after you’ve added the code to make it pass, you know where in your code to look to find the part that doesn’t work. This can also help you realize if your tests are trying to cover too wide a range of functionality, and if you might want to split the test into multiple parts to test smaller pieces of functionality.&lt;/p&gt;

&lt;p&gt;Now, about Rails controller tests. Controller tests are used to verify that all of your controller actions do as intended as well as checking that your routes function correctly. So naturally, they rely heavily on request types like &lt;code&gt;get&lt;/code&gt;, &lt;code&gt;post&lt;/code&gt;, &lt;code&gt;patch&lt;/code&gt;, and &lt;code&gt;delete&lt;/code&gt;. All of these request types have equivalent methods that you can use to check if the result of the request is successful, and that a &lt;code&gt;post&lt;/code&gt;, &lt;code&gt;patch&lt;/code&gt;, or &lt;code&gt;delete&lt;/code&gt; updated the database and redirected to the proper page.&lt;/p&gt;

&lt;p&gt;An example test for checking that the &lt;code&gt;index&lt;/code&gt; action in the &lt;em&gt;authors_contoller&lt;/em&gt; works could use the &lt;code&gt;get&lt;/code&gt; method with the path for the &lt;code&gt;Author&lt;/code&gt;’s &lt;em&gt;index&lt;/em&gt; page, then check that the url response is a success. The method would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test "should get index" do
   get authors_path
   assert_response :success
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In contrast to the &lt;code&gt;get&lt;/code&gt; method, &lt;code&gt;post&lt;/code&gt; and &lt;code&gt;patch&lt;/code&gt; need to use parameters to give the method the new information to create or update a record with. You would pass these params to the &lt;code&gt;post&lt;/code&gt; method like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;post authors_path, params: {
   author: { name: "Philip Pullman", age: 73 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another thing controller tests can check for is the three Hash objects you have access to after a request has been made and processed; &lt;code&gt;cookies&lt;/code&gt;, &lt;code&gt;flash&lt;/code&gt;, and &lt;code&gt;session&lt;/code&gt;. Say, for example, in my author’s create action I used a flash notice to add an alert whenever an author was created successfully. I could check it was working by adding a line like this to my test for creating new authors:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;assert_equal 'Author was successfully created.', flash[:notice]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One more useful thing that controller tests give you is access to three instance variables after a request is made: &lt;code&gt;@controller&lt;/code&gt; (the controller processing the request), &lt;code&gt;@request&lt;/code&gt; (the request object), and &lt;code&gt;@response&lt;/code&gt; (the response object). So, another way you could check that the &lt;code&gt;index&lt;/code&gt; action was working would be like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test "should get index" do
   get authors_path
   assert_equal "index", @controller.action_name
   assert_match "Authors", @response.body
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Of all of the different things I have talked about that you can add to your controller tests, you will probably find some more useful than others. I have only used a few in the example controller test file that I have here (the file is mostly the same as the one generated from the &lt;code&gt;scaffold&lt;/code&gt; command I ran for &lt;code&gt;authors&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# in controllers/authors_controller_test.rb
require 'test_helper'
class AuthorsControllerTest &amp;lt; ActionDispatch::IntegrationTest
   # method that is called before every test
   setup do
      @author = authors(:rowling)
   end
   test "should get index" do
      get authors_url
      assert_response :success
   end
   test "should get new" do
      get new_author_url
      assert_response :success
   end
   test "should create author" do
      assert_difference('Author.count') do
         post authors_url, params: {
            author: { name: "Philip Pullman", age: 73 }
         }
      end
      assert_redirected_to author_url(Author.last)
   end
   test "should show author" do
      get author_url(@author)
      assert_response :success
   end
   test "should get edit" do
      get edit_author_url(@author)
      assert_response :success
   end
   test "should update author" do
      patch author_url(@author), params: { author: { age: 56 } }
      assert_redirected_to author_url(@author)
   end
   test "should destroy author" do
      assert_difference('Author.count', -1) do
         delete author_url(@author)
      end
      assert_redirected_to authors_url
   end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With all of the types of tests I have covered in my four blog posts on Rails testing, I have given a pretty thorough introduction to writing tests for Rails applications. I have also given reasons for why writing tests is useful and practical when creating any kind of application. Ultimately, I have tried to convince you that you should consider writing tests for the next Rails app you create. Tests are very useful, and I hope my posts have made it seem doable to implement them in Rails.&lt;/p&gt;

</description>
      <category>testing</category>
      <category>rails</category>
    </item>
    <item>
      <title>Intro to Testing With Rails: System Tests</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Tue, 24 Nov 2020 01:20:55 +0000</pubDate>
      <link>https://dev.to/fosterv2/intro-to-testing-with-rails-system-tests-mab</link>
      <guid>https://dev.to/fosterv2/intro-to-testing-with-rails-system-tests-mab</guid>
      <description>&lt;p&gt;Writing full and complete tests for a Rails application requires testing each of the parts of the MVC pattern. For the Model component, you test that the methods in your models do all the things you want them to and that the relationships between your models work properly. I have gone over the basics of how you can write tests for you models in my previous two blog posts. In this one I will talk about how to start testing the View part of the MVC architecture by talking about how to test the way a user interacts with the webpages in your application.&lt;/p&gt;

&lt;p&gt;But first, I’m going to talk a bit about ways to figure out how many tests you should write. It is of course impossible to test for every possible thing that could happen when someone uses your app, and too many tests would take too long to run. But you also want to make sure you have enough tests to cover each range of possibilities. A good way to do this is by using edge cases and partitioning.&lt;/p&gt;

&lt;p&gt;Edge cases occur at an extreme, like a maximum or a minimum. For example, an empty string would be an edge case for strings. Partitioning is separating the inputs you are testing into groups of a similar type. An example of partitioning when testing numbers would be separating inputs into negative, positive, and zero. Then you only have to write three tests, each using one number in each partition. Using these methods you can write tests that hopefully cover every type of input a user could give while not writing a whole bunch of unnecessary tests.&lt;/p&gt;

&lt;p&gt;Getting back to Rails, the way to write tests for your views in Rails is system testing. All the files for this are kept in the &lt;em&gt;system&lt;/em&gt; folder under the &lt;em&gt;test&lt;/em&gt; directory. Now, unlike all the other types of tests I’ve talked about so far, a system test file is not generated by &lt;code&gt;rails g resource&lt;/code&gt;. But Rails does provide a generator to make system tests for each of your models:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; rails g system_test authors
      invoke  test_unit
      create    test/system/authors_test.rb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command creates a file for system tests for the &lt;em&gt;authors&lt;/em&gt; model (with a sample method). But since I used &lt;code&gt;rails g scaffold&lt;/code&gt;, and &lt;code&gt;scaffold&lt;/code&gt; does generate system test files, my &lt;em&gt;authors_test.rb&lt;/em&gt; file already had a variety of system tests written for &lt;em&gt;authors&lt;/em&gt;. The only thing I had to change was the line in the setup method to reference the &lt;code&gt;rowling&lt;/code&gt; fixture I had written earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# in system/authors_test.rb
require "application_system_test_case"
class AuthorsTest &amp;lt; ApplicationSystemTestCase
   setup do
      @author = authors(:rowling)
   end
   test "visiting the index" do
      visit authors_url
      assert_selector "h1", text: "Authors"
   end
   test "creating a Author" do
      visit authors_url
      click_on "New Author"
      fill_in "Age", with: @author.age
      fill_in "Name", with: @author.name
      click_on "Create Author"
      assert_text "Author was successfully created"
      click_on "Back"
   end
   test "updating a Author" do
      visit authors_url
      click_on "Edit", match: :first
      fill_in "Age", with: @author.age
      fill_in "Name", with: @author.name
      click_on "Update Author"
      assert_text "Author was successfully updated"
      click_on "Back"
   end
   test "destroying an Author" do
      visit authors_url
      page.accept_confirm do
         click_on "Destroy", match: :first
      end
      assert_text "Author was successfully destroyed"
   end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;System tests are noticeably different from the other tests I have talked about before. For one thing, they are not automatically run when you run the &lt;code&gt;rails test&lt;/code&gt; command. You have to either specify the system test file you want to run, like rails test &lt;code&gt;test/system/authors_test.rb&lt;/code&gt; or, to run all you system tests, in the command line run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; rails test:system
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another thing different about system tests is how you are not just using assertions anymore, you are using Capybara to interact with the webpage. From the tests in &lt;em&gt;authors_test.rb&lt;/em&gt; above, you can see from the intuitively named methods that you can tell the test to visit a given url path, click on certain buttons, and fill in form inputs. All of this is supposed to mirror how a user would interact with a webpage. For more information on what kinds of methods Capybara has, you can look through their &lt;a href="https://github.com/teamcapybara/capybara#the-dsl"&gt;documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Another interesting thing about system tests is that when they are run, they use a browser window. When I ran &lt;code&gt;rails test:system&lt;/code&gt; it opened a new google chrome window for each of the tests, and if you watch one window you can see it doing the things defined in the test, like navigating from page to page and filling in and submitting forms. But it all moved so fast it was difficult to see what happened, and to help with this Rails has the &lt;em&gt;ScreenshotHelper&lt;/em&gt;. You can add &lt;code&gt;take_screenshot&lt;/code&gt; or &lt;code&gt;take_failed_screenshot&lt;/code&gt; at any point in your tests to take a screenshot of the browser window running the test. &lt;em&gt;ScreenshotHelper&lt;/em&gt; is very helpful in debugging how something went wrong.&lt;/p&gt;

&lt;p&gt;Now, the reason my system tests opened a chrome window was because it was configured that way. There is a file in the top level of the &lt;em&gt;test&lt;/em&gt; directory that is generated every time you start a Rails application (as long as it’s not an API) called &lt;em&gt;application_system_test_case.rb&lt;/em&gt;. This file is for configuring your system tests and the default configuration looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require "test_helper"
class ApplicationSystemTestCase &amp;lt; ActionDispatch::SystemTestCase
   driven_by :selenium, using: :chrome, screen_size: [1400, 1400]
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The “driver” in &lt;code&gt;driven_by&lt;/code&gt; determines where the tests are run, in a browser window or in your terminal or another type of window. You can also specify what browser you would like to use with &lt;code&gt;using&lt;/code&gt;. The &lt;code&gt;screen_size&lt;/code&gt; argument defines what size you’d like the browser window to be. This argument can be very useful if you want to test how your app looks on mobile. If you plan on having your app used on mobile you can create a separate file with configurations for the mobile &lt;code&gt;screen_size&lt;/code&gt; and have some tests for mobile that &lt;code&gt;require&lt;/code&gt; and inherit from your mobile configured file instead of &lt;em&gt;ApplicationSystemTestCase&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;I think it’s clear that system tests are a very important part of thoroughly testing a Rails application. I have now covered how to start writing tests for both the M and V parts of the MVC framework. In my next post I’ll go into testing the Controller component of the MVC pattern by going into how to begin writing tests for your controller actions.&lt;/p&gt;

</description>
      <category>testing</category>
      <category>rails</category>
    </item>
    <item>
      <title>Intro to Testing With Rails: The Test Database and Fixtures</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Tue, 24 Nov 2020 01:19:52 +0000</pubDate>
      <link>https://dev.to/fosterv2/intro-to-testing-with-rails-the-test-database-and-fixtures-14lo</link>
      <guid>https://dev.to/fosterv2/intro-to-testing-with-rails-the-test-database-and-fixtures-14lo</guid>
      <description>&lt;p&gt;Testing is undeniably an important part of web development. Continuing on from my last blog post, I am going to give more information about how to write tests with Ruby on Rails in this post. This post will be easier to understand if you read my last one, Intro to Testing With Rails. This one picks up where I left off, and explains more of the structure of the testing framework that Rails provides.&lt;/p&gt;

&lt;p&gt;But before I get into that, I’ll talk a bit about the mindset a developer should have when writing tests. Sometimes it can be hard for a developer to write tests because you need to have a different mindset from when you are creating parts of your application. When writing out the features of an app, you want to focus on all ways your app will &lt;strong&gt;work&lt;/strong&gt;. But, when writing tests you have to think about all the ways your app could &lt;strong&gt;break&lt;/strong&gt;. Sometimes it can be hard to think about breaking your app when you worked so hard to make it function the way you want it to, but you need to think in this mindset to write good tests.&lt;/p&gt;

&lt;p&gt;Now back to Rails testing. One thing you should have is a separate database specifically for testing. Most of the parts of the your application are going to interact heavily with a database, but when you are testing you are usually going to be writing bad data in an attempt to see if things break. Also, you will most likely be running the tests over and over again, and you don’t want all of the data you made in your tests to be added to the database multiple times. This is why we have a test database. Once again, Rails has already taken care of this problem for you. By default, every Rails app has three environments: development, test, and production, and there is a database for each of them. They are configured in &lt;code&gt;config/database.yml&lt;/code&gt; and created when you run &lt;code&gt;rails db:setup&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;One way Rails uses the test database is with fixtures. Fixtures are sample data that Rails will automatically add to the test database each time your tests are run. Fixtures can be very useful because you don’t have to create a new instance of a model for every test you write, you can just reference one that’s already in your database. Fixtures are written in a file with a &lt;em&gt;.yml&lt;/em&gt; file extension and they look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# in fixtures/authors.yml
rowling:
  name: J. K. Rowling
  age: 55
# in fixtures/books.yml
harry:
  title: Harry Potter
  author: rowling
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;em&gt;authors.yml&lt;/em&gt; and &lt;em&gt;books.yml&lt;/em&gt; files these fixtures are written in were generated when I used the &lt;code&gt;rails g scaffold&lt;/code&gt; commands. Whenever you generate a new model Rails will automatically create a new file for fixtures of that model (with examples) in the &lt;em&gt;test/fixtures&lt;/em&gt; directory.&lt;/p&gt;

&lt;p&gt;As you can see from the examples, there is a specific format to fixtures. Each is given a name (anything you want to call it) which is followed by an indented list of the model’s attributes followed by a colon and whatever value you want to give the attribute. Also, notice how the &lt;em&gt;books&lt;/em&gt; fixture references the &lt;em&gt;author&lt;/em&gt; fixture. This is completely valid and, just by writing &lt;code&gt;rowling&lt;/code&gt;, Rails will know that you are referencing the &lt;code&gt;rowling&lt;/code&gt; fixture in the &lt;em&gt;authors.yml&lt;/em&gt; file.&lt;/p&gt;

&lt;p&gt;Now, to use the fixtures in your tests you have to reference them like this: &lt;code&gt;authors(:rowling)&lt;/code&gt; or, to get a list, &lt;code&gt;authors(:rowling, :author_two)&lt;/code&gt; will return an array with two fixtures. Once you have a reference to a fixture, you can treat it the same as any other instance of the class, such as using any of the methods the class might have on the fixture.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;This is an example of a passing test using fixtures:
# in models/book_test.rb
test "fixtures properly save to database" do
  assert_not_nil books(:harry), 
      "book fixture did not save to database"
  assert_equal authors(:rowling), books(:harry).author, 
      "book fixture does not reference author fixture"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, so far I’ve only changed Rails-generated files in two folders in the &lt;em&gt;test&lt;/em&gt; directory: &lt;em&gt;models&lt;/em&gt; and &lt;em&gt;fixtures&lt;/em&gt;. As I just explained, files in the &lt;em&gt;fixtures&lt;/em&gt; folder are for creating sample data to run your tests on. In the &lt;em&gt;models&lt;/em&gt; folder you write tests to test the methods in all your model classes using assertions. So, as yet, I have only written tests for my models in the &lt;em&gt;models&lt;/em&gt; folder. But testing the behavior of your models is by no means sufficient to prove that a Rails app works as intended.You also need to test how a user can interact with the app. In other words, test the controllers and routing.&lt;/p&gt;

&lt;p&gt;Testing you controller actions and what shows up on a web page uses a different system of writing tests using a gem called &lt;a href="https://github.com/teamcapybara/capybara"&gt;Capybara&lt;/a&gt;. In my next bog post on testing with Rails I will focus on how you can use Capybara to test a user’s interaction with web pages in a Rails app.&lt;/p&gt;

</description>
      <category>testing</category>
      <category>rails</category>
    </item>
    <item>
      <title>Intro to Testing With Rails</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Tue, 24 Nov 2020 01:19:40 +0000</pubDate>
      <link>https://dev.to/fosterv2/intro-to-testing-with-rails-3n1c</link>
      <guid>https://dev.to/fosterv2/intro-to-testing-with-rails-3n1c</guid>
      <description>&lt;p&gt;Many developers will rely on interacting with an app to prove it works the way they want. But this is not the most efficient way to do things. Writing tests for your code is a good practice, and it can save time finding bugs down the line. In this series of blog posts, I’m going to talk about how to write tests for a Rails application.&lt;/p&gt;

&lt;p&gt;First, I’ll talk a bit about why testing is so important. Writing tests is useful because you can use them to check that a small piece of your code works the way it was intended. This is also a good way to become more familiar with your code, because it forces you to thinks about what exactly you want each piece of your code to do. And when you find a bug in your code you can have a better idea of where it is, because you know for sure that certain things work. Also, once you’ve written a test, you can run it over and over to check that everything still works as expected, even after you have made a major change to your app.&lt;/p&gt;

&lt;p&gt;Writing tests in Rails is relatively easy. A Rails application started with &lt;code&gt;rails new&lt;/code&gt; already has a testing framework set up for you, in a folder called &lt;em&gt;test&lt;/em&gt;. It has a file structure like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- test
  - channels/
  - controllers/
  - fixtures/
  - helpers/
  - integration/
  - mailers/
  - models/
  - system/
  - application_system_test_case.rb
  - test_helper.rb
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each of the folders in test are designed to &lt;em&gt;test&lt;/em&gt; a specific part of your application, and I’ll go into each of them in a later blog post. For this one, I’ll just focus on the basics of writing and running tests.&lt;/p&gt;

&lt;p&gt;As an example, I’ll make references to files in a project created with these commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; rails g scaffold Author name age:integer
~ // ♥ &amp;gt; rails g scaffold Book title author_id:integer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you use a rails generator like &lt;code&gt;rails g scaffold&lt;/code&gt; or &lt;code&gt;rails g resource&lt;/code&gt; to create files for your models, rails will automatically create some test files for these models that you can fill in. In the &lt;em&gt;models&lt;/em&gt; folder I have a file like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# author_test.rb
require 'test_helper'
class AuthorTest &amp;lt; ActiveSupport::TestCase
# test "the truth" do
#   assert true
# end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The class &lt;em&gt;AuthorTest&lt;/em&gt; inherits from &lt;em&gt;ActiveSupport::TestCase&lt;/em&gt; which gives us a number of useful methods, including the one used in the example commented out here. The &lt;em&gt;test&lt;/em&gt; method takes a test name(here, the name is &lt;code&gt;“the truth”&lt;/code&gt;) and a block(everything between the &lt;code&gt;do&lt;/code&gt; and &lt;code&gt;end&lt;/code&gt;), and if you give it a descriptive name, it can be very clear what the test is designed to look for.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;do…end&lt;/code&gt; block is an assertion. Assertions are designed to evaluate something for expected results. There are a variety of available assertions, and there is a full list of them &lt;a href="https://guides.rubyonrails.org/testing.html#available-assertions"&gt;here&lt;/a&gt;. Each test can have as many assertions as you want, and the test will only pass if all the assertions are successful. An example assertion for my Authors/Books project test that an author will not save without a name. A test to check for this could look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test "author should not save without name" do
  author = Author.new
  assert_not author.save
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we have a test written, we need to be able to run it and see the results. There are a variety of ways to run your tests; you could run all of them at once with &lt;code&gt;rails test&lt;/code&gt;, but this isn’t very efficient. Running all of your tests can take longer, so if you just want to check the results of a specific test, the best way is to drill down to run just the tests in the file, or even the test on a given line. So the command to run the test I wrote would look like this (7 being the line the test starts on):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;~ // ♥ &amp;gt; rails test test/models/author_test.rb:7
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But, because I never wrote the validation to require an &lt;em&gt;author&lt;/em&gt; to have a name into my &lt;em&gt;Author&lt;/em&gt; model class, the test fails, and it denotes the failure with an &lt;em&gt;F&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Running:
F
Failure:
AuthorTest#test_author_should_not_save_without_name 
[/path/rails-testing/test/models/author_test.rb:17]:
Expected true to be nil or false
rails test test/models/author_test.rb:7
Finished in 1.116573s, 0.8956 runs/s, 0.8956 assertions/s.
1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Unfortunately, this failure isn’t very descriptive about what exactly went wrong. That’s because I didn’t give the assertion a massage to output so it used the default, &lt;em&gt;“Expected true to be nil or false”&lt;/em&gt;. To make the test clearer I can add a message, and I’ll also add another assertion to check that an author cannot be saved with an age that is not positive:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test "should not save if validations fail" do
  author = Author.new
  assert_not author.save, "saved the author without a name"
  author = Author.new(name: "J. K. Rowling", age: -10)
  assert_not author.save, "saved the author with a non-positive age"
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then I’ll add the validations to the model file like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#author.rb
class Author &amp;lt; ApplicationRecord
  has_many :books
  validates :name, presence: true
  validates :age, numericality: { greater_than: 0 }
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Running the test now gives me a passing result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Running:
.
Finished in 0.267856s, 3.7333 runs/s, 7.4667 assertions/s.
1 runs, 2 assertions, 0 failures, 0 errors, 0 skips
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is one more result you can get from running a test, and that is an error. The same as in any other code, errors can occur from spelling mistakes or references to variables that don’t exist. For example, if I had misspelled &lt;code&gt;assert_not&lt;/code&gt; as &lt;code&gt;asset_not&lt;/code&gt; (which I did), the result would look like this, with an &lt;em&gt;E&lt;/em&gt; to designate the error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Running:
E
Error:
AuthorTest#test_should_not_save_if_validations_fail:
NoMethodError: undefined method `asset_not' for 
#&amp;lt;AuthorTest:0x00007fea2ffdd178&amp;gt;
    test/models/author_test.rb:12:in `block in &amp;lt;class:AuthorTest&amp;gt;'
rails test test/models/author_test.rb:7
Finished in 0.766280s, 1.3050 runs/s, 1.3050 assertions/s.
1 runs, 1 assertions, 0 failures, 1 errors, 0 skips
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The error helpfully points to the line where it occurred, on line 12 in &lt;em&gt;author_test.rb&lt;/em&gt;. It also ran the first assertion before it found the error in the second one and stopped.&lt;/p&gt;

&lt;p&gt;And this is most of what you need to know about the basics of testing in rails. In summary, you write tests in blocks that use assertions to verify the results you expect. Then you run the tests and, if you are clear in your test massages, the results give helpful information about any tests that didn’t pass. In my next blog post I’ll go into the types of tests to write in each of the directories that Rails gives you in the &lt;em&gt;test&lt;/em&gt; folder.&lt;/p&gt;

</description>
      <category>testing</category>
      <category>rails</category>
    </item>
    <item>
      <title>Routing in React With React Router</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Sat, 14 Nov 2020 01:08:15 +0000</pubDate>
      <link>https://dev.to/fosterv2/routing-in-react-with-react-router-19j2</link>
      <guid>https://dev.to/fosterv2/routing-in-react-with-react-router-19j2</guid>
      <description>&lt;p&gt;People who work with React should know that it is essentially a single page application (SPA). But but many React applications don’t present that way to a user. The user interacts with things on the page, and different components appear and disappear. A user interacts with the application as if it has many pages, so it makes sense for the URL to reflect this. This is where &lt;a href="https://github.com/ReactTraining/react-router"&gt;React Router&lt;/a&gt; comes in.&lt;/p&gt;

&lt;p&gt;First of all, since React is a SPA, all routing is Client-Side routing. This is in comparison to server side routing where each different URL makes a different GET request to the server. In Client-Side routing, the only thing the server does is render the HTML with the &lt;code&gt;'root' div&lt;/code&gt; for React to render it’s virtual DOM. One benefit of this is the speed with which the different “pages” will appear for the user. The Client-Side route will just swap which component is rendered to the page instead of making a new server call, which can take some time. But on the flip side, the first page may take longer to load.&lt;/p&gt;

&lt;p&gt;The best way to use Client-Side routing in React is to use React Router. This is a React library that uses specific URLs to tell React what components to render at each URL. To use it you have to install &lt;code&gt;react-router-dom&lt;/code&gt; to your React app by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install react-router-dom
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, to use &lt;code&gt;react-router-dom&lt;/code&gt;, you have to decide what file or files you want to define the routes in your React app. The most common places for this is in index.js or the App component if you need to pass state down the component tree. App is usually where you keep the logic of how to organize the application, so it makes sense that it is the component that decides which components to show at each route. You also want to decide what routes you want to have.&lt;/p&gt;

&lt;p&gt;For example, lets say you have a React application with a three main components: &lt;code&gt;Home&lt;/code&gt;, &lt;code&gt;About&lt;/code&gt;, and &lt;code&gt;FriendList&lt;/code&gt;, which shows info about each friend in a list you have. At the top of the App.js file you would need to import all the components along with &lt;code&gt;react-router-dom&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Home from './Home'
import About from './About'
import FriendList from './FriendList'
import { BrowserRouter as Router, Route } from 'react-router-dom'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Importing &lt;code&gt;BrowserRouter&lt;/code&gt; as &lt;code&gt;Router&lt;/code&gt; is a common convention, so instead of using the term &lt;code&gt;BrowserRouter&lt;/code&gt; in the component, you refer to it as &lt;code&gt;Router&lt;/code&gt;. There are other things you can import from &lt;code&gt;react-router-dom&lt;/code&gt;, but these are the main ones you’ll want to use to apply Client-Side routing.&lt;/p&gt;

&lt;p&gt;Now that you’ve got everything imported, you’ll want to use the &lt;code&gt;Router&lt;/code&gt; and &lt;code&gt;Route&lt;/code&gt; components in the JSX returned from the App component (either the &lt;code&gt;render&lt;/code&gt; method of a class component, or the &lt;code&gt;return&lt;/code&gt; of a functional component):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return (
  &amp;lt;Router&amp;gt;
    &amp;lt;div&amp;gt;
      &amp;lt;Route exact path=”/” component={Home} /&amp;gt;
      &amp;lt;Route exact path=”/about” component={About} /&amp;gt;
      &amp;lt;Route exact path=”/friends” component={FriendList} /&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/Router&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To unpack this example, first we’ll talk about the &lt;code&gt;Router&lt;/code&gt; component. It is the base of our application’s routing, so it is where we declare how React Router will be used. It can also only have one child element, so that is why all the &lt;code&gt;Route&lt;/code&gt; components are wrapped in a &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Next we’ll talk about the &lt;code&gt;Route&lt;/code&gt; component. In this example, they are taking two props, which basically equate to them saying “when the URL matches this &lt;code&gt;path&lt;/code&gt;, render the given &lt;code&gt;component&lt;/code&gt;.” The &lt;code&gt;exact&lt;/code&gt; part just makes sure that the component is only rendered when the URL matches the path exactly. If we omitted the &lt;code&gt;exact&lt;/code&gt; from all of the &lt;code&gt;Route&lt;/code&gt;s, the &lt;code&gt;Home&lt;/code&gt; component would render at any path with a &lt;code&gt;“/”&lt;/code&gt; in it, in other words at every path.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Route&lt;/code&gt; can also be given the prop of &lt;code&gt;render&lt;/code&gt; instead of &lt;code&gt;component&lt;/code&gt;. &lt;code&gt;Render&lt;/code&gt; takes a callback function as input so our example &lt;code&gt;Route&lt;/code&gt;s would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Route exact path=”/” render={() =&amp;gt; &amp;lt;Home /&amp;gt;} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using &lt;code&gt;render&lt;/code&gt; is best when you have props from App that you want to send to it’s child components. It also has default props that you can pass through the callback function.&lt;/p&gt;

&lt;p&gt;Another helpful thing &lt;code&gt;react-router-dom&lt;/code&gt; has is the &lt;code&gt;NavLink&lt;/code&gt; and &lt;code&gt;Link&lt;/code&gt; components. When you import and use either of these components you can add links throughout your pages to other pages in the application. Both components function almost the same way, except you can add styling to &lt;code&gt;NavLink&lt;/code&gt;s that show what page you are currently on. So for our example you could have a component called &lt;code&gt;Navbar&lt;/code&gt; that you render on every page that looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NavLink } from 'react-router-dom'
const Navbar = () =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;NavLink to=”/” exact&amp;gt;Home&amp;lt;/NavLink&amp;gt;
      &amp;lt;NavLink to=”/about” exact&amp;gt;About&amp;lt;/NavLink&amp;gt;
      &amp;lt;NavLink to=”/friends” exact&amp;gt;Friends&amp;lt;/NavLink&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is one last piece of routing functionality we are missing, and that is the ability to show the individual friends from our friend list at an individual page. The URL for this is commonly &lt;code&gt;'/friends/1'&lt;/code&gt;, the &lt;code&gt;1&lt;/code&gt; being the id of the friend being shown. Writing individual routes for each friend would be ridiculous, so the way we do this is with nested routes.&lt;/p&gt;

&lt;p&gt;This requires some refactoring, so first off, we have to change App’s &lt;code&gt;FriendList&lt;/code&gt; route to look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Route
  path='/friends'
  render={props =&amp;gt; {
    &amp;lt;FriendList {...props} friends={this.state.friends}/&amp;gt;
  }}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This &lt;code&gt;Route&lt;/code&gt; uses &lt;code&gt;render&lt;/code&gt; so that it can have access to a list of movies from state and the list of &lt;code&gt;props&lt;/code&gt; with information about the route.&lt;/p&gt;

&lt;p&gt;Then the &lt;code&gt;FriendList&lt;/code&gt; component will render a list of &lt;code&gt;Link&lt;/code&gt;s that each go to show page for a friend with the URL &lt;code&gt;'/friends/:id'&lt;/code&gt; with the &lt;code&gt;id&lt;/code&gt; being the id of the friend that’s being shown. It also defines a new &lt;code&gt;Route&lt;/code&gt; that uses the &lt;code&gt;match&lt;/code&gt; prop passed down:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const FriendList = ({ match, friends }) =&amp;gt; {
  const renderFriends =&amp;gt; {
    return friends.map(friend =&amp;gt; {
      return &amp;lt;Link key={friend.id} to={`/friends/${friend.id}`}&amp;gt;
        {friend.name}
      &amp;lt;/Link&amp;gt;
    })
  };
  return (
    &amp;lt;div&amp;gt;
      {renderFriends()}
      &amp;lt;Route
        path={`${match.url}/:friendId`}
        render={props =&amp;gt; &amp;lt;Friend {...props} friends={friends} /&amp;gt;}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we need a way for the &lt;code&gt;Friend&lt;/code&gt; component to know which friend from the list it should display. We do this through the &lt;code&gt;match&lt;/code&gt; prop again:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Friend = ({ match, friends }) =&amp;gt; {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h3&amp;gt;{ friends[match.params.friendId].name }&amp;lt;/h3&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And with this we have fully functioning routes for visiting a a specific &lt;code&gt;friend&lt;/code&gt; from the list.&lt;/p&gt;

&lt;p&gt;Routing for an application may seem minor when thinking about the entirety of an application, but it can actually be very important. A user could have a favorite page in an app, and if they want to bookmark it, they need a URL to save. Routes can also be expressive to the user about what a certain page of an app is doing. Ultimately, routing is something all developers should take into careful consideration when designing their applications.&lt;/p&gt;

</description>
      <category>react</category>
      <category>routing</category>
    </item>
    <item>
      <title>The Basics of Scraping with Ruby</title>
      <dc:creator>Valerie Foster</dc:creator>
      <pubDate>Sat, 14 Nov 2020 00:47:15 +0000</pubDate>
      <link>https://dev.to/fosterv2/the-basics-of-scraping-with-ruby-15bb</link>
      <guid>https://dev.to/fosterv2/the-basics-of-scraping-with-ruby-15bb</guid>
      <description>&lt;p&gt;There will be a number of times when you will want to get data from the internet for a program you are writing. APIs are a great resource, but only if one exists with the subject matter you want and if the data you are looking for is static and unchanging. If you want information about the upcoming events for your favorite celebrity or the approaching games for the Seahawks or Mariners, APIs don’t cut it. Scraping is a great way to get data from a webpage.&lt;/p&gt;

&lt;p&gt;Scraping is the process of extracting data from a webpage. It can refer to manually copying the data from the page, but it usually refers programmatically parsing the data you need from the HTML of the webpage. The best way to scrape with Ruby is to use the Nokogiri gem and Open-URI. Open-URI is just used to get the HTML from the link you pass it then Nokogiri does all of the interesting stuff.&lt;/p&gt;

&lt;p&gt;The name Nokogiri comes from Japanese meaning “a fine-toothed saw” that was used for the rough ripping of logs into boards for carpenters and cabinetmakers. And thats how the Nokogiri gem is used. It precisely scrapes the only the necessary data that we are looking for from a webpage.&lt;/p&gt;

&lt;p&gt;To use Nokogiri you first have to install the gem then require it and Open-URI at the top of your file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require 'nokogiri'
require 'open-uri'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then to start you need to get the HTML from whatever website you want data from using the url:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;html = open('http://www.google.com')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and once you have this Nokogiri will take the string of HTML returned and translate it into a NodeSet that we can mess with (it is conventional to call this ‘doc’):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;doc = Nokogiri::HTML(html)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now doc has all the HTML converted into nested nodes, which is similar to the structure of nested hashes, so we can iterate over the Nokogiri object to find the information we want.&lt;/p&gt;

&lt;p&gt;Now that we have the fundamentals done can get to the interesting stuff: getting the data we’re looking for from ‘doc’. Nokogiri uses css selectors to return data from a specific part of the HTML document. Css selectors look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div id="example-div"&amp;gt;
  &amp;lt;p class="example-paragraph"&amp;gt;Example paragraph&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example you would refer to the div element with #example-div (# for ids) and the paragraph with .example-paragraph (. for class). In HTML an id has to be unique and only refers to one element, while a class can be applied to a group of similar elements.&lt;/p&gt;

&lt;p&gt;Using the Nokogiri in the doc variable to look for the element you want is possible, but not very practical seeing as it is a very long list of information. The best way to find what you want is to find it on the original webpage, right click it, and choose inspect. This will show you the HTML of the whole webpage, but it will highlight the item you clicked on.&lt;/p&gt;

&lt;p&gt;Back to Ruby, Nokogiri has a .css method that is called on the doc variable. It takes an argument of the css selector you want to find using the approach from the previous paragraph, with classes and ids. So getting the paragraph from the example above would look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;doc.css(".example-paragraph")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this actually returns something similar to an array with one Nokogiri object with a bunch of information about the whole paragraph element. If you want to get only the text part of the paragraph you would call .text on the end:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;doc.css(".example-paragraph").text
  =&amp;gt; "Example paragraph"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it isn’t very interesting to grab information from only one part of a webpage, and this is where iteration comes in. If an animal shelter website had a list of div elements for every adoptable pet, you could find the class name for all of those divs and call pets = doc.css(“.class-name”) to get a collection of elements, then iterate over them using an enumerable to get the names of all of the pets, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pets.map do |pet|
   pet.css(".pet-name").text
end
  =&amp;gt; [array of pet names]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s clear to see that scraping is a powerful tool to get data from the internet, but there are a number of drawbacks. One is that it might take time to find what you’re looking for. Another is that you might have to write vastly different code to scrape from one website compared to another. But the biggest problem is that if a website changes the scraper you wrote probably won’t work anymore. But even with these stumbling blocks scraping is still much faster and easier than having to manually enter data.&lt;/p&gt;

</description>
      <category>ruby</category>
      <category>scraping</category>
      <category>nokogiri</category>
    </item>
  </channel>
</rss>
