-
gemfile
添加:
group :development, :test do
gem 'rspec-rails', '~> 5.0.0'
end
bundle install
bin/rails generate rspec:install
-
bin/rails generate rspec:model user
:生成spec/models/user_spec.rb
;或者rails g rspec:request items
生成请求测试文件
require 'rails_helper' // 相当于import外面的一些帮助方法
RSpec.describe User, type: :model do
it "有email" do
user = User.new email: "xiaowu@qq.com"
expect(user.email).to eq "xiaowu@qq.com"
end
end
- 配置测试环境数据库:
database.yml
配置:
test:
<<: *default
database: mangosteen_test
username: mangosteen
password: 123456
host: db-for-mangosteen
- 创建数据库:
RAILS_ENV=test bin/rails db:create
- 创建表:
RAILS_ENV=test bin/rails db:migrate
bundle exec rspec
测试请求(Rspec每次请求完会自动清空数据表)
-
bin/rails g rspec:request items
生成对应的items_spec.rb
- 代码示例:
require "rails_helper"
RSpec.describe "Items", type: :request do
describe "index by page" do
it "works! (now write some real specs)" do
11.times { Item.create amount: 100 }
expect(Item.count).to eq(11)
get "/api/v1/items"
expect(response).to have_http_status(200)
json = JSON.parse(response.body)
expect(json["resources"].size).to eq(10)
get "/api/v1/items?page=2&per_page=5"
expect(response).to have_http_status(200)
json = JSON.parse(response.body)
expect(json["resources"].size).to eq(5)
end
end
describe "create" do
it "can create an item" do
expect {
post "/api/v1/items", params: { amount: 99 }
}.to change { Item.count }.by(+1)
expect(response).to have_http_status 200
json = JSON.parse response.body
expect(json["resource"]["id"]).to be_an(Numeric)
expect(json["resource"]["amount"]).to eq 99
end
end
end
bundle exec rspec