spec(3) - controller

没有测试的代码就是耍流氓

  1. rspec(1) - summary
  2. specs(2) - model
  3. specs(3) - controller
  4. specs(4) - request
  5. specs(5) - mock
  6. [specs(6) - mailer]
  7. [specs(7) - view]
  8. [specs(8) - routing]
  9. [specs(9) - helper]
  10. [specs(10) - factory-girl]
  11. [specs(11) - fake other gems]
  12. [specs(12) - sidekiq]
  13. [specs(13) - db migration]
  14. [specs(14) - timecop]
  15. [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

你可能感兴趣的:(spec(3) - controller)