Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 简化rspec单元测试_Ruby_Unit Testing_Rspec - Fatal编程技术网

Ruby 简化rspec单元测试

Ruby 简化rspec单元测试,ruby,unit-testing,rspec,Ruby,Unit Testing,Rspec,在rspec的单元测试中,很多时候都必须同时指定上下文和let,这有点麻烦,而且似乎没有必要。例如: context 'type = :invalid' do let(:type) { :invalid } it { expect { subject }.to raise_error(ArgumentError) } end RSpec.shared_examples "some thang" do |type| it { expect { subject }.to raise_e

在rspec的单元测试中,很多时候都必须同时指定上下文和let,这有点麻烦,而且似乎没有必要。例如:

context 'type = :invalid' do
  let(:type) { :invalid }

  it { expect { subject }.to raise_error(ArgumentError) }
end
RSpec.shared_examples "some thang" do |type|
 it { expect { subject }.to raise_error(ArgumentError) }
end

RSpec.shared_examples "a thang" do
  include_examples "some thang", :invalid
  # Or whatever is more appropriate for your domain
  # I.e., If you're testing subclass behavior use it_should_behave_like()
end
如果我能做一些类似的事情,那会更好(通过大量测试总结):

let_context type: :invalid do
  it { expect { subject }.to raise_error(ArgumentError) }
end

该方法将为我定义一个上下文和let(s),上下文的参数类似于
type=:invalid
let(:type){:invalid}
,因为除了这个变量已更改这一事实之外,我没有什么要说的了。

实际上,通过以下一些建议,您可以得到更少的行数:

context 'type = :invalid' do
  let(:type) { :invalid }
  it { expect{ subject }.to raise_error(ArgumentError)
end
您的变体可以理解为

它会引发一个错误,但subject会引发错误

虽然这更干净

它期望主体提出错误

尽管如此,它还是很离题:)

UPD

哦。实际上,您不能将两个块传递给方法,所以下面的示例不是有效的Ruby:)

而你的例子

let_context type: :invalid do
  ...
end
不会像
let
那样执行惰性执行

在rspec中的单元测试中,很多时候必须同时指定上下文和let,这有点麻烦

听起来你可能想用一个

更新

RSpec为您建议的语法提供了DSL:。例如:

context 'type = :invalid' do
  let(:type) { :invalid }

  it { expect { subject }.to raise_error(ArgumentError) }
end
RSpec.shared_examples "some thang" do |type|
 it { expect { subject }.to raise_error(ArgumentError) }
end

RSpec.shared_examples "a thang" do
  include_examples "some thang", :invalid
  # Or whatever is more appropriate for your domain
  # I.e., If you're testing subclass behavior use it_should_behave_like()
end

是的,我看过(偶尔也会用到)共享上下文,它会很有帮助,但在本例中,我说的是为每个
上下文
块设置一个
it
(其中每个
上下文
块只定义一个
let
)。如果(type::invalid){expect{subject}引起{u error}是的,这是一个很好的观点。实际上,我将一些规范转换为使用这种语法。这肯定更好,但不能回答主要问题;)基于此编辑问题。当我挑剔的时候:为什么你不能使用
expects
。说它{期望的
It,读起来会很好“{ /代码〉。我认为你可以在RSPEC配置文件中别名方法,所以我可以考虑这个问题;”@布里安安德伍德,为什么<>代码>  >与<代码>上下文< /代码>分开。在你的情况下,<>代码> LeTyValueType::无效的DO /代码>你缺少隔离。其次是懒惰。这是非常重要的要求。测试。你不想得到难以调试的副作用:)是的,那么
let_context type:->{:invalid}
呢。虽然使用procs/lambdas是一个非常尴尬的解决方案,但开始变得不那么方便:)