rails rspec - (2nd test) Expected response to be a

2019-07-27 01:28发布

问题:

Expected response to be a <:redirect>, but was <200>

My tests has:

describe "Link POST #create" do

  context "with valid attributes" do
    it "creates a new link" do
      expect{
        post :create, link: FactoryGirl.create(:link, :group => @group)
      }.to change(Link,:count).by(1)
    end

    it "redirects to the new link" do
      post :create, link: FactoryGirl.create(:link, :group => @group)
      # response.should redirect_to @link # Link.unscoped.last
      response.should redirect_to Link.unscoped.last # render_template :show
    end
  end

The first test passes but the second fails.

My code is:

  def create
    @link = Link.new(params[:link])

    respond_to do |format|
      if @link.save
        flash[:notice] = 'Link was successfully created.'
        format.html { redirect_to(@link) }
        format.xml  { render :xml => @link, :status => :created, :location => @link }
      else
        @selected_group = params[:group_id]
        format.html { render :action => "new" }
        format.xml  { render :xml => @link.errors, :status => :unprocessable_entity }
      end
    end
  end

I've tried redirect and render but can't get the 2nd test to pass.

回答1:

Here's something that should make it work:

describe "Link POST #create" do

  context "with valid attributes" do

    def do_post( format = 'html' )
      attributes = FactoryGirl.build(:link).attributes.merge( :group_id => @group.id )
      post :create, :link => attributes, :format => 'html'
    end

    it "creates a new link" do
      expect{
        do_post
      }.to change(Link,:count).by(1)
    end

    it "redirects to the new link" do
      do_post
      response.should redirect_to( assigns[:link] )
    end
  end

The first spec was working only because you were calling FactoryGirl.create so a record was being created out of the controller, but most likely the controller call wasn't working.