kurenn / market_place_api

The API on Rails tutorial application
142 stars 70 forks source link

Authenticable #authenticate_with_token spec passes without writing any code #62

Open ghost opened 8 years ago

ghost commented 8 years ago
  describe "#authenticate_with_token" do
    before do
      @user = FactoryGirl.create(:user)
      allow(authentication).to receive(:current_user).and_return(nil)
      allow(response).to receive(:response_code).and_return(401)
      allow(response).to receive(:body).and_return({ "errors" => "Not authenticated"}.to_json)
      allow(authentication).to receive(:response).and_return(response)
    end

    it "returns error message as JSON" do
      expect(json_response[:errors]).to eql("Not authenticated")
    end

    it { should respond_with(401) }
  end
module Authenticable
  def current_user
    @current_user ||= User.find_by(auth_token: request.headers['Authorization'])
  end
end

Specs are passing regardless of writing any code for the spec. I'm wondering why stub out the entire workings of the function, but not even call the function that is being tested.

kurenn commented 8 years ago

It is probably not the btes approach, in my mind I thought it was being tested indirectly by stubbing everything and once the call arrives, everything just will work, any thoughts on this?

ghost commented 8 years ago

The call never arrives though?

ghost commented 8 years ago
  controller(ApplicationController) do
    include Authenticable
    before_action :authenticate_with_token!

    def dummy_action;end;
  end

  describe "#authenticate_with_token!" do
    before do
      routes.draw { get 'dummy_action' => 'anonymous#dummy_action' }
      @user = FactoryGirl.create(:user)
      allow(authentication).to receive(:current_user).and_return(nil)
      get :dummy_action
    end

    it "returns error message as JSON" do
      expect(json_response[:errors]).to eql("Not authenticated")
    end

    it "returns a 401 response code" do
      expect(response.status).to eq(401)
    end
  end

This worked. Creating an anonymous controller allowed me to test whether the method existed, and returned the correct response.

kurenn commented 8 years ago

That is nice, I'll include that on the second edition version of the book and make the reference to you ;)

ghost commented 8 years ago

Sweet! Much appreciated.