我想要在同一控制器中的各种操作中测试以下测试。我怎么能干这个?在下面的评论中,您将看到测试应根据我正在测试的操作调用不同的方法和操作。
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
答案 0 :(得分:3)
你可以这样做:
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
答案 1 :(得分:1)
一个选项可能是提供一个模块混合,其中包含一个包含规范的方法。
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