ruby-on-rails - RSpec - 如何创建可用于自动嵌入 "it"测试的测试的辅助方法

标签 ruby-on-rails ruby rspec

我是 ruby​​/rails/rspec 等新手。

使用 rspec 2.13.1,我想创建一个模块,该模块具有可以从我的测试中调用的方法,从而导致后续调用 RSpec::Core::ExampleGroup 的“it”方法。

我的模块:

require 'spec_helper'

module TestHelper
  def invalid_without(symbols)
    symbols = symbols.is_a?(Array) ? symbols : [symbols]
    symbols.each do |symbol|
      it "should not be valid without #{symbol.to_s.humanize}" do
        # Gonna nullify the subject's 'symbol' attribute here
        # and expect to have error on it
      end
    end
  end
end

上面的代码被添加到:

spec/support/test_helper.rb

在我的spec_helper.rb中,在RSpec.configure block 中,我添加了以下内容:

config.include TestHelper

现在,在测试中,我执行以下操作:

describe Foo
    context "when invalid" do
        invalid_without [:name, :surname]
    end
end

运行这个,我得到:

undefined method `invalid_without' for #<Class:0x007fdaf1821030> (NoMethodError)

感谢任何帮助..

最佳答案

使用shared example group .

shared_examples_for "a valid array" do |symbols|
  symbols = symbols.is_a?(Array) ? symbols : [symbols]
  symbols.each do |symbol|
    it "should not be valid without #{symbol.to_s.humanize}" do
      # Gonna nullify the subject's 'symbol' attribute here
      # and expect to have error on it
    end
  end
end

describe Foo do
  it_should_behave_like "a valid array", [:name, :surname]
end

关于ruby-on-rails - RSpec - 如何创建可用于自动嵌入 "it"测试的测试的辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069873/

相关文章:

ruby - 需要忽略基本的 http 身份验证

Ruby 生成自签名证书

ruby - 将 ruby​​ 日期转换为字符串而不丢失格式

javascript - 如何在 Capybara 和 Selenium 中打开浏览器

ruby - 使用不同的参数多次运行 rspec 测试套件

ruby-on-rails - 两个表上的 Rails where 子句

ruby-on-rails - 多种类型的太阳黑子搜索与单一类型的太阳黑子搜索

ruby-on-rails - 使用 YAJL 在 Rails 中拉取流式 API

javascript - 在 Rails 3 + dygraphs 上作图

RSpec/Capybara 请求规范——无法让设计发布新用户 session