When starting out with RSpec, there were things that confused me, and that I couldn’t find a lot of information about online. For example, by writing, expect(user).to be_valid we are making the assertion that the user object is valid. The expect method allows us to make assertions about the expected code behavior. We are only interested in testing its validation. We don’t use User.create! here, because we don’t want to actually save the record. Next, we use User.new to create a new instance of the User model with a different name and password, but with the same email. The ! at the end of the method will help us by raising an error if the user can’t be saved. First, we create a new user record and save it directly to the database with the User.create! command. Within the block it "is invalid with a duplicate email address" we are testing if the email already exists. With User.create! you create a new user record and immediately save it to the database in one go. To save it to the database, we need to run a separate user.save command. User.new creates a completely new instance of the User model, but does not save it to the database. Though they are similar, they do work slightly differently. In Ruby on Rails User.new and User.create are both methods that can be used to create a new instance of the User class. If you want to temporarily exclude a test example for your test without deleting it, you can use xit instead of it. it takes a string argument that describes what the test is testing. With every line that starts with it a new, individual test case begins. The describe method has a set of expectations, for example, what a model should look like. With 'require 'rails_helper' we are loading the Rails application environment, and require access to the rails app.ĭescribe outlines the general functionality of the class or feature you're testing. RSpec needs to know where your Rails app is and where to find its components. Let’s break down step by step what we just wrote. It 'is invalid with a duplicate email address' doĮxpect(user.errors).to include('has already been taken')Įnter fullscreen mode Exit fullscreen mode It 'is valid with a name, email, and password' doĮxpect(user.errors).to include("can't be blank") Before we get into testing with Rspec, let’s write a very simple user model. One of the most important models for that app would be the user model. Now, imagine we would be creating a second Instagram app.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |