【问题标题】:Testing sequence of events with RSpec使用 RSpec 测试事件序列
【发布时间】:2012-05-27 13:46:32
【问题描述】:

我刚开始使用 RSpec,我正在尝试做一些非常微不足道的事情,但我找不到任何好的文档来说明这样做的好方法。我想测试一系列事件,比如两个用户之间的友谊。

我的规格是:

describe User do

  describe "friendships" do
    describe ".friends?" do
      before do
        @user1 = FactoryGirl.build(:user)
        @user2 = FactoryGirl.build(:user)
      end

      it "should be false for non friends" do
        @user1.friends?(@user2).should be false
        @user2.friends?(@user1).should be false
      end

      it "should be false for requested friendship" do
        Friendship.create(:user_id => @user1.id, :friend_id => @user2.id)  # 1
        @user1.friends?(@user2).should be false
        @user2.friends?(@user1).should be false
      end

      it "should be true for accepted friendship" do
        Friendship.for_users(@user1, @user2).update_attribute(:approved, true) # 2
        @user1.friends?(@user2).should be true
        @user2.friends?(@user1).should be true
      end
    end

  end
end

我正在标记为# 1 的行上建立友谊,并希望它出现在# 2 行,但我猜数据库会在两者之间刷新。

这是测试此类事件流的错误方法吗?我应该做什么?任何指针将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    是的,数据库在事件流之间被刷新。

    最好的测试方法是让每个测试都设置好所需的内容,并在完成后将其丢弃。这样一来,每个测试都是完全独立的,因此您不必依赖以前的测试来处理以后的测试。

    你可以考虑只在工厂女孩中建立友谊,然后测试友谊是否存在,然后在集成测试中通过 UI 让人们成为朋友并检查相同的事情

    【讨论】:

    • 废话。我很确定我错过了什么。
    【解决方案2】:

    我猜你正在寻找context。像这样的:

    context "when friends" do
      before { Friendship.create ... }
    
      it "should be false for requested friendship"
    
      it "should be true for accepted friendship"
    end
    

    很抱歉,您应该看看 rspec 文档:basic structure (describe/it)

    【讨论】:

    • 在这种情况下,第一个 it 和第二个 it 之间的变化是否持续存在?
    • 没有。只是为每个示例执行了before 块。
    • 但正如我在问题中提到的,友谊对象的状态会发生变化,以便从请求变为接受。在这种情况下,上下文有何帮助?
    • 它在before 块中发生变化,对吗?在每个示例之前执行。每个示例都应该单独运行。在一个例子中依赖另一个例子真的没有任何意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2013-07-04
    • 2011-01-20
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多