使用 rspec 进行测试时,将常见的“测试实用方法”放在哪里?
假设您有一个销售小部件的购物网站。但是,每个小部件的库存都是有限的,因此保持“widget.number_still_available”数字最新非常重要。
我想编写一个 rspec 测试,类似于
it "always displays the correct number still available" do
# Assume there is a before method that sets up a widget with 5 available
widget.number_still_available.should == 5
# User "[email protected]" purchases 2 widgets
widget.number_still_available.should == 3
# User "[email protected]" purchases 1 widget
widget.number_still_available.shhould == 2
# User "[email protected]" cancels purchase of 1 widget
widget.number_still_available.should == 4
end
我希望能够编写执行“购买”和“取消”方法的仅测试方法。由于多种原因,这些操作与我的模型中的任何“真实”方法都不对应(最重要的是 PHP 中有一个解耦的后端系统,它执行部分购买和取消操作)。
使用 RSpec 时,放置此代码的正确位置在哪里?在黄瓜中,我可以编写几个步骤 - 但我不确定 RSpec 的正确等效项是什么。
Suppose you have a shopping site that sells widgets. However, the inventory of each widget is limited, so it's important to keep the "widget.number_still_available" number up to date.
I'd like to write an rspec test along the lines of
it "always displays the correct number still available" do
# Assume there is a before method that sets up a widget with 5 available
widget.number_still_available.should == 5
# User "[email protected]" purchases 2 widgets
widget.number_still_available.should == 3
# User "[email protected]" purchases 1 widget
widget.number_still_available.shhould == 2
# User "[email protected]" cancels purchase of 1 widget
widget.number_still_available.should == 4
end
I'd like to be able to write testing-only methods that performs the "purchasing" and "canceling" methods. These actions don't correspond to any "real" methods in my models for a variety of reasons (most significantly there is a decoupled back-end system in PHP that performs part of the purchasing and canceling actions).
Where is the correct place to put this code when using RSpec? In cucumber, I could write a couple of steps - but I'm not sure what the correct equivalent is for RSpec.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议在
spec/support
中创建一个名为purchase_helpers.rb
的新文件,并将以下内容放入其中:这样做的好处而不是将其放入
spec /spec_helper.rb
的优点是它不会用大量与 RSpec 设置无关的代码挤满该文件。将事情分开是更好的做事方式。I would suggest making a new file in
spec/support
calledpurchase_helpers.rb
and put this content in it:The benefit of doing this rather than chucking it into
spec/spec_helper.rb
is that it is not crowding up that file with a lot of unrelated-to-the-setup-of-RSpec code. Separating things out is the better way to do things.您可以将 Monkeypatch 放入 spec_helper.rb 中,或者直接放在规范文件的顶部(如果它仅用于该文件)。
使用现有类方法创建辅助方法会更加清晰和安全,而不是对类进行猴子修补。
You can drop a monkeypatch into spec_helper.rb, or directly at the top of the spec file if it's only used for that one file.
It would be more clear and safe to make helper methods which use existing class methods, instead of monkeypatching the classes.