【问题标题】:rspec variables in different contexts/scopes不同上下文/范围中的 rspec 变量
【发布时间】:2011-06-22 13:23:01
【问题描述】:

我正在尝试使用 rspec 做一些事情,但我无法在我需要的地方访问我需要的变量。例如:

describe "some things" do
  it "should have things in App" do
    App.things.should_not be_nil #no problems here
    # puts App.things.count
    # => 10
  end

 # puts App.things.count
 # => 0
 App.things.each do |thing|
   #this doesn't work at all as App.things is empty 
   it "#{thing.title} should have an account number" do
      thing.acc_no.should_not be_nil  
   end
 end

我猜这是因为调用不同块的时间。或者也许我完全没有抓住重点。

我需要遍历“事物”并对每个事物做出断言,但我不能这样做,因为事物在 describe 块的上下文中没有任何元素,只有在 it 块中。

有什么帮助吗?

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    看来你做错了:为什么要测试集合的每一个值?

    • 创建一些夹具并测试 App 是否具有正确数量的已创建对象

    • 使用创建的夹具之一来测试具有正确值、运行验证等...

    至少,您可以使用 rspec 的共享示例来重复常见测试:

    http://blog.davidchelimsky.net/2010/11/07/specifying-mixins-with-shared-example-groups-in-rspec-2/

    【讨论】:

    • 我正在使用水豚进行测试。我需要确保 dom 中的对象具有正确的状态。
    • 所以使用 capybara 的 xpath 并迭代结果,但该代码将不起作用。顺便说一句,创建 1 个测试并在其中检查(例如在 2 个数组之间进行比较)
    【解决方案2】:

    我不知道这是否有帮助,但我遇到了类似的问题。我想迭代“it”块的原因是 rspec 失败消息将包含我正在迭代的事物的名称。

    在我的例子中,它是一系列 dom id,可能包含也可能不包含 div,具体取决于页面上不同对象的状态。

    所以我做到了:

    %w{preliminary_project_proposal final_project_proposal progress_report preliminary_abstract final_abstract preliminary_presentation final_presentation}.each do |id|
      it "should not show a late message for #{id}" do
        within "##{id}" do
          page.should_not have_css('.late_assignment')          
        end            
      end        
    end
    

    这很好用。正如您所指出的,我无法将数组赋值移动到变量或方法,这意味着它出现在几个地方,这不是很漂亮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-13
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多