我写了大部分Rspec规格,但我面临一个重要问题。我已经在我的所有路由上设置了路由约束(这本身可能是有争议的)。只有允许IP地址(存储在单独的IpAddress模型中)的管理员才能访问我的应用程序中的某些区域。
长话短说,我想模拟或存根我的约束模型,以便我可以自由访问我的规范中的所有内容。
我的约束如下:
class IpAddressConstraint
def initialize
@ips = IpAddress.select('number')
end
def matches?(request)
if @ips.find_by_number(request.remote_ip).present? || Rails.env.test? #<- temporary solution
true
else
if @current_backend_user.present?
backend_user_sign_out
else
raise ActionController::RoutingError.new('Not Found')
end
end
end
end
MyApp::Application.routes.draw do
constraints IpConstraint.new do
#all routes
end
end
在Rspec中测试此路由约束的最佳方法是什么?目前我添加了一个条件,所以如果我在我的测试环境中,我可以完全跳过这些约束。如果我能以某种方式模拟这种约束会更好。
答案 0 :(得分:1)
这样的事情:
describe "Some Feature" do
context "from allowed ip" do
before(:each) {IpAddress.create(number: '127.0.0.1')}
it "should allow access to foo" do
.....
end
....
end
context "from non allowed ip" do
it "shouldn't allow access to foo" do
.....
end
end
然后,您可以将创建的IP地址提取到辅助模块或函数,尤其是在需要进行更复杂的设置时。如果您一直希望它在那里,您可以将它添加到您的spec_helper文件配置块中,以便在每个/每个规范之前运行,但是那时您将更难以测试它是否成功阻止了非授权的ips。