" Relationship.count"没有改变2.预期:6实际:4

时间:2014-11-02 23:06:14

标签: ruby-on-rails testing controller

在我编写此测试之前,我的所有测试都已通过 - 在编写以下测试后,它失败了。通常情况下,测试会给你提示在哪里修复测试,但这只显示:

 FAIL["test_should_successfully_create_2_user_relationship_objects", RelationshipsControllerTest, 1.146038]
 test_should_successfully_create_2_user_relationship_objects#RelationshipsControllerTest (1.15s)
        "Relationship.count" didn't change by 2.
        Expected: 6
          Actual: 4
        test/controllers/relationships_controller_test.rb:193:in `block in <class:RelationshipsControllerTest>'

  74/74: [=====================================================================================================================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.14952s
74 tests, 180 assertions, 1 failures, 0 errors, 0 skips

第193行是:

assert_difference 'Relationship.count', 2 do

但我现在不知道在哪里解决这个问题。我对Rails相当新,并且不知道如何对此进行故障排除。任何提示在哪里看都将非常感谢!我不确定代码如何流动以尝试执行测试以了解从哪里开始查看。

据我所知,这是相关的代码:

relationships_controller_test.rb:

  test "should successfully create 2 user relationship objects" do
    assert_difference 'Relationship.count', 2 do
      post :create, relationship: { followed_id: users(:firstname).name }
    end
  end

模型/ relationship.rb:

# makes sure 2 relationships are created otherwise none are created. 
  def self.request(user1, user2)
    transaction do
      relationship1 = create!(follower: user1, followed: user2, state: 'pending')
      relationship2 = create!(follower: user2, followed: user1, state: 'requested')

      relationship1.send_request_email
      relationship1
    end
  end

relationship_controller.rb:

def create
    if params[:relationship] && params[:relationship].has_key?(:followed_id)
      # @followed = User.find(params[:relationship][:followed_id])
      @followed = User.where(name: params[:active_relationship][:followed_id]).first
      @active_relationship = Relationship.request(current_user, @followed)
      if @active_relationship.new_record?
        flash[:danger] = "There was a problem creating that relationship request"
      else
        flash[:success] = "Friend request sent"
      end
      redirect_to followed_path(@followed)
    else
      flash[:danger] = "Friend Required"
      redirect_to users_path
    end
  end

夹具/ relationships.yml:

一个:   追随者:名字   紧随其后:firstname3

2:   追随者:名字   紧随其后:firstname4

3:   追随者:firstname3   紧随其后:名字

4:   追随者:firstname2   紧随其后:名字

1 个答案:

答案 0 :(得分:0)

在您的控制器中,您似乎引用了params[:active_relationship] - 这应该是params[:relationship]吗?如果未提供该参数,则控制器代码似乎会抛出错误。

调试问题的一个好方法是运行rails console并尝试模仿控制器的行为。这将为您提供有关错误位置的更多具体信息。或者,您可以使用debugger gem(或rails 4中的byebug)在控制器代码中放置断点。这样您就可以准确地查看传递给控制器​​的参数,并且还允许您一次一行地执行代码。