导轨rspec的 - (第二测试)预期响应是一个<:重定向>,但<200>(

2019-10-16 20:29发布

预期响应是一个<:重定向>,但<200>

我的测试有:

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

第一测试通过,但第二失败。

我的代码是:

  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

我试过重定向和渲染,但不能得到第二次测试通过。

Answer 1:

这里的东西应该使其工作:

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

第一个规范是工作,只是因为你叫FactoryGirl.create这样一个纪录被创造出来的控制器,但最有可能的控制器通话不能正常工作。



文章来源: rails rspec - (2nd test) Expected response to be a <:redirect>, but was <200>