[英]How to DRY up RSpec tests shared by different actions in same controller
我有以下测试,我想通过同一个 controller 中的各种操作进行测试。 我怎样才能把它弄干? 在下面的评论中,您会看到测试应该调用不同的方法和操作,具体取决于我正在测试的操作。
shared_examples_for "preparing for edit partial" do
it "creates a new staff vacation" do
StaffVacation.should_receive(:new)
get :new
end
it "assigns @first_day_of_week" do
get :new
assigns(:first_day_of_week).should == 1
end
end
describe "GET new" do
# i want to use 'it_behaves_like "preparing for edit partial"'
# and it should use 'get :new'
end
describe "GET edit" do
# i want to use 'it_behaves_like "preparing for edit partial"'
# but it should use 'get :edit' instead
end
describe "POST create" do
# on unsuccessful save, i want to use 'it_behaves_like "preparing for edit partial"'
# but it should use 'post :create' instead
end
你可以这样做:
shared_examples_for "preparing for edit partial" do
let(:action){ get :new }
it "creates a new staff vacation" do
StaffVacation.should_receive(:new)
action
end
it "assigns @first_day_of_week" do
action
assigns(:first_day_of_week).should == 1
end
end
context 'GET new' do
it_should_behave_like 'preparing for edit partial' do
let(:action){ get :new }
end
end
context 'GET edit' do
it_should_behave_like 'preparing for edit partial' do
let(:action){ get :edit }
end
end
context 'POST create' do
it_should_behave_like 'preparing for edit partial' do
let(:action){ post :create }
end
end
或者,您可以对示例使用某种循环:
['get :new', 'get :edit', 'post :create'].each do |action|
context action do
it "creates a new staff vacation" do
StaffVacation.should_receive(:new)
eval(action)
end
it "assigns @first_day_of_week" do
eval(action)
assigns(:first_day_of_week).should == 1
end
end
end
一种选择可能是提供一个模块混合,其中包含一个包含您的规范的方法。
include Auth # This is your module with your generalized spec inside a method
it "redirects without authentication" do
unauthorized_redirect("get", "new")
end
然后,在我们的方法中,我们可以通过不同类型的授权进行循环:
module Auth
def unauthorized_redirect(request, action)
[nil, :viewer, :editor].each do |a|
with_user(a) do
eval "#{request} :#{action}"
response.should redirect_to login_path
# whatever other expectations
end
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.