[英]How to make these RSpec tests more DRY in Rails
I have a bunch of recurring tests for some of my controller actions, all of which require authentication. 我对我的一些控制器操作进行了一系列重复测试,所有操作都需要进行身份验证。 As a result, you end up seeing a lot of code like the following: 因此,您最终会看到许多代码,如下所示:
describe "authentication requests" do
it "should return 401 for unauthenticated :show" do
get :show
...
end
it "should return 401 for unauthenticated :create" do
post :create
...
end
end
Is there a better way to DRY this code up so that any action in the controller that needs authentication can be described in one test? 有没有更好的方法来干这个代码,以便控制器中需要身份验证的任何操作都可以在一个测试中描述?
If you need to replicate the tests across controllers, you can use rspec macros. 如果需要跨控制器复制测试,可以使用rspec宏。 Create a spec/macros/controller_macros.rb
with a method like so: 使用如下方法创建spec/macros/controller_macros.rb
:
def should_return_401_for_unauthenticated(test_controller)
describe test_controller, "authentication requests" do
it "should return 401 for show" do
get :show
response.code.should == "401"
end
it "should return 401 for create" do
post :create
response.code.should == "401"
end
end
end
Then in each controller spec that needs the tests: 然后在每个需要测试的控制器规范中:
describe MyController do
should_return_401_for_unauthenticated(self)
end
I'm not an rspec user, but you could do something like: 我不是rspec用户,但你可以这样做:
describe "authentication requests" do
limited_access = [:show, :create]
limited_access.each do |action|
it "should return 401 for unauthenticated :#{action}" do
get action
## assert response 401
end
end
end
Or to just have one test: 或者只进行一次测试:
describe "authentication requests" do
limited_access = [:show, :create]
it "should return 401 for unauthenticated #{limited_access.to_sentence}" do
limited_access.each do |action|
get action
## assert response 401
end
end
end
Could add a spec_helper method to abstract it for you ... The possibilities are endless. 可以添加一个spec_helper方法来为你抽象......可能性是无穷无尽的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.