3

我正在关注 Michael Hartl 的Ruby on Rails 教程

我到达了第 11.37 章,但我的测试失败了。我收到以下错误:

Failure/Error: xhr :post, :create, relationship: { followed_id: other_user.id }
ArgumentError:
bad argument (expected URI object or URI string)

我是 Ruby on Rails 的新手,所以我真的不知道出了什么问题。有人可以帮助解决此错误吗?

控制器/relationships_controller.rb:

class RelationshipsController < ApplicationController
  before_action :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

特征/relationships_controller_spec.rb:

require 'spec_helper'

describe RelationshipsController, type: :request do

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

  before { sign_in user, no_capybara: true }

  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 }
      expect(response).to 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
      expect(response).to be_success
    end
  end
end
4

2 回答 2

9

xhr本教程所依赖的版本,它以一个方法作为第二个参数,来自ActionController::TestCase::Behavior. 该模块仅包含在 rspec-rails gem 的控制器视图测试中。您正在从 Rails 中选择另一个版本xhr,期望路径作为第二个参数,因此您得到的错误。

controller您需要通过将其包含在controllers目录中或显式设置测试类型来确保您的测试属于类型。因为您在features目录中进行了测试并且没有以其他方式键入,所以它不被视为控制器测试。(注意:教程中的图 11.37 确实有测试驻留在spec/controllers目录中。)

于 2013-08-31T16:26:02.063 回答
3

xhr 方法似乎接收路径而不是操作名称。所以如果你替换它应该可以工作

xhr :post, relationships_path, relationship: { followed_id: other_user.id }
于 2013-08-31T14:58:24.457 回答