【问题标题】:rspec - redirect to Group.last going to wrong recordrspec - 重定向到 Group.last 去错误的记录
【发布时间】:2012-06-03 19:36:28
【问题描述】:

39 次测试通过,但 1 次失败。

Expected response to be a redirect to <http://test.host/groups/11> 
but was a redirect to <http://test.host/groups/12>

我创建了一条新记录并尝试重定向到show,但我的一条记录“关闭”。

看起来可能有点缓存/重新加载问题?

我的 rspec 测试:

describe "POST #create" do

  ...

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

    it "redirects to the new group" do
      post :create, group: FactoryGirl.attributes_for(:group)
      response.should redirect_to Group.last
    end
  end

  ...

我的代码:

  # POST /groups
  # POST /groups.xml
  def create
    @group = Group.new(params[:group])

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

结果:

计数发生变化(测试通过),但 last 记录的直接敌人,即我得到:

 Failure/Error: response.should redirect_to Group.last
   Expected response to be a redirect to <http://test.host/groups/11> 
   but was a redirect to <http://test.host/groups/12>

【问题讨论】:

  • Rails 3.2.4 有一个类似这样的奇怪错误 - 如果您使用的是 3.2.4,您是否尝试过 3.2.5?

标签: testing rspec rspec2 factory-bot


【解决方案1】:

答案是模型(组)将按组名排序作为默认范围。

修复只是在测试中使用Group.unscoped.last

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多