简体   繁体   English

在 rspec-rails 中编写步骤?

[英]Writing steps in rspec-rails?

I'm just getting into testing and I'm wondering how to write steps for RSpec specs, so I can reuse a lot of functions such as logging in, etc.我刚刚开始测试,我想知道如何为 RSpec 规范编写步骤,这样我就可以重用很多功能,例如登录等。

Usually tests should be in isolation from one another;通常测试应该彼此隔离; if a lot of your tests need to do the same thing, that suggests that they're duplicating some work.如果你的很多测试都需要做同样的事情,这表明他们在重复一些工作。 But sometimes that's unavoidable -- you'll frequently need to have a logged-in user handy to test authenticated things, for example.但有时这是不可避免的——例如,您经常需要有一个方便的登录用户来测试经过身份验证的东西。

Especially in the case of Ruby testing, chances are very good that someone has already written a library to solve the specific problem you want.特别是在 Ruby 测试的情况下,很有可能有人已经编写了一个库来解决您想要的特定问题。 For example, it's very common to need some data existing before an operation can be tested properly -- and that is why factory_girl exists.例如,在正确测试操作之前需要一些数据是很常见的——这就是factory_girl存在的原因。

If you want to do behavior-driven integration testing that walks through all the steps a user would actually do, you should use Cucumber instead.如果您想进行行为驱动的集成测试以遍历用户实际执行的所有步骤,则应改用Cucumber

If you want to reuse methods across different places, you can put shared code in spec/support :如果你想在不同的地方重用方法,你可以把共享代码放在spec/support中:

# spec/support/consumable_helper.rb
module ConsumableHelper
  def consume(consumable)
    calories = consumable.om_nom_nom
  end
end

RSpec.configure do |config|
  config.include ConsumableHelper
end

If you want to test the same behavior in multiple areas, use shared_examples_for and it_behaves_like :如果您想在多个区域测试相同的行为,请使用shared_examples_forit_behaves_like

shared_examples_for "a Consumable" do
  it "should be delicious" do
    subject.should be_delicious
  end

  it "should provide nutrition" do
    subject.calories.should > 0
  end
end

describe Fruit do
  it_behaves_like "a Consumable"
end

describe Meat do
  it_behaves_like "a Consumable"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM