rspec controller redirect test failing due to different domain

时间:2016-06-18 20:13:29

标签: ruby-on-rails rspec

Using Rails 4.0, rspec 3.4 (and Capybara 2.7), I have a very simple controller and controller spec. Authentication is via devise 3.5:

Model:

class DraftsController < ApplicationController
  before_action :set_draft, only: [:show, :destroy]
  before_filter :authenticate_user!, except: [:index]

  respond_to :html

  def index
    @drafts = Draft.all
    respond_with(@drafts)
  end

  def show
    respond_with(@draft)
  end

  def new
    @draft = Draft.new
    respond_with(@draft)
  end

  def create
    @draft = Draft.new(draft_params)
    @draft.save
    respond_with(@draft)
  end

  def destroy
    @draft.destroy
    respond_with(@draft)
  end

  private
    def set_draft
      @draft = Draft.find(params[:id])
    end

    def draft_params
      params.require(:draft).permit(:name)
    end
end

Spec (abridged)

require 'rails_helper'

RSpec.describe DraftsController, type: :controller do
  let(:valid_attributes) {
    { name: 'Test One' }
  }

  context "when signed in" do
    login_user

    describe "DELETE #destroy" do
      it "redirects to the drafts list" do
        draft = Draft.create! valid_attributes
        delete :destroy, {:id => draft.to_param}
        expect(response).to redirect_to(drafts_url)
      end
    end
  end

end

My test.rb environment file defines:

config.after_initialize do
  Rails.application.routes.default_url_options[:host] = 'localhost:3000'
end

When I run the test, it fails with:

  1) DraftsController when signed in DELETE #destroy redirects to the drafts list
     Failure/Error: expect(response).to redirect_to(drafts_url)

       Expected response to be a redirect to <http://localhost:3000/drafts> but was a redirect to <http://test.host/drafts>.
       Expected "http://localhost:3000/drafts" to be === "http://test.host/drafts".

It seems that the test is generating the url based on Rails' config, but some part of the test framework (I don't know where) is supplying the host as test.host. How can I make them agree?

0 个答案:

没有答案