use*_*003 0 ruby rspec ruby-on-rails
假设我有各种RSpec context块来对具有类似数据场景的测试进行分组.
feature "User Profile" do
context "user is active" do
before(:each) { (some setup) }
# Various tests
...
end
context "user is pending" do
before(:each) { (some setup) }
# Various tests
...
end
context "user is deactivated" do
before(:each) { (some setup) }
# Various tests
...
end
end
Run Code Online (Sandbox Code Playgroud)
现在我正在添加一个新功能,我想添加一个简单的场景,当我点击用户页面上的某个链接时验证行为
it "clicking help redirects to the user's help page" do
click_on foo_button
expect(response).to have('bar')
end
Run Code Online (Sandbox Code Playgroud)
理想情况下,我很乐意为所有3个上下文添加此测试,因为我希望确保它在不同的数据场景下正确执行.但是测试本身并没有从上下文变为上下文,因此将它全部输入3次似乎是重复的.
干燥这个测试集有哪些替代方案?我可以将新测试粘贴到某个模块中,还是RSpec有一些内置功能让我定义一次并从每个context块调用它?
谢谢!
您可以使用shared_examples...在spec/support/shared_examples.rb中定义它们
shared_examples "redirect_help" do
it "clicking help redirects to the user's help page" do
click_on foo_button
expect(response).to have('bar')
end
end
Run Code Online (Sandbox Code Playgroud)
然后在每个上下文中输入...
it_behaves_like "redirect_help"
Run Code Online (Sandbox Code Playgroud)
您甚至可以将块传递给该块it_behaves_like,然后使用该action方法执行该块,该块对于每个上下文都是唯一的.
你shared_example可能看起来像......
shared_examples "need_sign_in" do
it "redirects to the log in" do
session[:current_user_id] = nil
action
response.should render_template 'sessions/new'
end
end
Run Code Online (Sandbox Code Playgroud)
在你的背景下,你会用块来称呼它......
describe "GET index" do
it_behaves_like "need_sign_in" do
let(:action) {get :index}
end
...
Run Code Online (Sandbox Code Playgroud)