RailsTutorial 11.2.5 Ajax调用没有返回成功

时间:2012-12-08 06:23:02

标签: jquery ajax rspec ruby-on-rails-3.2 railstutorial.org

在Rails 3.2版本的Railstutorial(.org)的11.2.5部分中,我无法让所有的relations_controller_spec.rb测试通过,即“应该成功响应”方法和破坏关系。尽管使用了所提供代码的精确重复(复制和粘贴)。收到的邮件是expected success? to return true, got false

如果它在某种程度上相关,我的关注/取消关注按钮没有在网络浏览器中更新,但我能够通过激活app / assets / javascripts / application.js中的= require jquery来解决这个问题。这一步似乎没有在教程文本中的任何地方提到过)。在此修复之前,未呈现关联的create.js.erb和destroy.js.erb操作。

现在应用程序似乎正在运行,包括ajaxified follow / unfollow按钮(它们都在屏幕上更新并按预期修改关系)。尽管如此,提到的两个rspec测试仍然失败。我已经分析了服务器日志,但到目前为止这没有给我任何线索。

relationships_controller_spec.rb

require 'spec_helper'

describe RelationshipsController do

  let(:user) { FactoryGirl.create(:user) }
  let(:other_user) { FactoryGirl.create(:user) }

  before { sign_in user }

  describe "creating a relationship with Ajax" do

    it "should increment the Relationship count" do
      expect do
        xhr :post, :create, relationship: { followed_id: other_user.id }
      end.to change(Relationship, :count).by(1)
    end

    it "should respond with success" do
      xhr :post, :create, relationship: { followed_id: other_user.id }
      response.should be_success
    end
  end

  describe "destroying a relationship with Ajax" do

    before { user.follow!(other_user) }
    let(:relationship) { user.relationships.find_by_followed_id(other_user) }

    it "should decrement the Relationship count" do
      expect do
        xhr :delete, :destroy, id: relationship.id
      end.to change(Relationship, :count).by(-1)
    end

    it "should respond with success" do
      xhr :delete, :destroy, id: relationship.id
      response.should be_success
    end
  end
end

relationships_controller.rb

class RelationshipsController < ApplicationController
  before_filter :signed_in_user

  def create
    @user = User.find(params[:relationship][:followed_id])
    current_user.follow!(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end
end

可以在https://github.com/spinnn/testapp

找到app repo

我注意到了

Button doesn't update in Ajax - Rails Tutorial 3 at §12.2.5

但是这个讨论在这种情况下似乎并不适用(它也与Rails 3.0而不是Rails 3.2版本的教程有关)。

我已经采取了多次重启Web服务器以及重置,重新填充和重新准备数据库的步骤,而没有解决问题。

我在OS X上使用ruby 1.9.3p286和Rails 3.2.8。我们非常感谢有关解决这个问题的任何建议。

1 个答案:

答案 0 :(得分:0)

好的,是时候羞怯了。在克隆railstutorial / sample_app_2nd_ed.git之后,我发现了一个非常直接的解决方案。 relationships_controller.rb已被复制,app / controllers /中的副本和spec(控制器/)中的(冗余)副本不幸的是,我试图调试的版本是冗余版本,真实版本不完整。捂脸。也许是警示故事。