Rspec Practices 1

U should add gem rspec-rails in ur project’s Gemfile, then bundle.

Then, u need run command rails g rspec:install.

When u use rails commands, likes rails g model User xx:xx. It will help u to create spec/models/user_spec.rb file.

Yes, Rspec will check _spec.rb file as test file.

Give me some codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
require 'rails_helper'

RSpec.describe User, :type => :model do
  context "signup with" do
    it "email and password, then success." do
      expect(User.signup("123@exmaple.com", "123456").errors.size).to eq(0)
    end
    it "illege email and password, then fail." do
      expect(User.signup("123sdf", "123456").errors.size).to eq(1)
    end

    it "email and no password, then fail. " do
      expect( User.signup("123@example.com", "").errors.size ).to eq(1)
    end
  end
end

and then, u can use rspec to test all _spec files, or u can only test user_spec.rb file with rspec spec/models/user_spec.rb command.

if no error, u can get

1
3 examples, 0 failures

It is not a good view. We just not work for testing, but say something to others.

U can run rspec --format doc, will get result:

1
2
3
4
5
6
7
User
  signup with
    email and password, then success.
    illege email and password, then fail.
    email and no password, then fail.

3 examples, 0 failures

Comments