【问题标题】:rails rspec - (2nd test) Expected response to be a <:redirect>, but was <200>rails rspec -(第二次测试)预期的响应是 <:redirect>,但是是 <200>
【发布时间】:2012-06-10 03:36:40
【问题描述】:

预期的响应是 <:redirect>,但是是

我的测试有:

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

我已尝试重定向和渲染,但无法通过第二次测试。

【问题讨论】:

  • FactoryGirl.create(:link, :group =&gt; @group) 是给你一个对象还是对象属性的散列?

标签: ruby-on-rails ruby testing rspec controller


【解决方案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,因此从控制器中创建了一条记录,但很可能控制器调用不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多