没有测试的代码就是耍流氓
- rspec(1) - summary
- specs(2) - model
- specs(3) - controller
- specs(4) - request
- specs(5) - mock
- [specs(6) - mailer]
- [specs(7) - view]
- [specs(8) - routing]
- [specs(9) - helper]
- [specs(10) - factory-girl]
- [specs(11) - fake other gems]
- [specs(12) - sidekiq]
- [specs(13) - db migration]
- [specs(14) - timecop]
- [specs(15) - jenkins]
以前文讲过的User为例来讲解rails中controller的测试。
生成UserController的测试
rails generate rspec:controller user
create spec/controllers/user_controller_spec.rb
添加index的测试
require "rails_helper"
RSpec.describe UserController, :type => :controller do
describe "GET #index" do
it "responds successfully with an HTTP 200 status code" do
get :index
expect(response).to be_success
expect(response).to have_http_status(200)
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
end
it "loads all of the User into @users" do
user1, user2 = User.create!, User.create!
get :index
expect(assigns(:users)).to match_array([user1, user2])
end
end
describe "GET #new" do
it "responds successfully with HTTP 200 status code"
get :new
expect(response).to be_success
expect(response).to have_http_status(200)
end
it "renders the new template" do
get :new
expect(response).to render_template("new")
end
end
describe "POST #create" do
it "create a user" do
lambda do
post :create, {user : { name: "zql" } }
end.should change(User, :count).by(1)
expect {
post :create, {user: {name: "zql"} }
}.to change(User, :count).by(1)
end
end
describe "PUT #update" do
before do
@user = User.create
end
it "update a user" do
lambda do
put :update, {user: {name: "zql"} }
end.should change(User, :count).by(0)
@user.reload.name.should eq "zql"
end
end
descible "DELETE #destroy" do
before do
@user = User.create
end
it "destroy a object" do
lambda do
delete :destroy, {id: @user.id}
end.should change(User, :count).by(-1)
@user.reload.id.should be_nil
end
end
end
网友评论