Eth*_*han 15 testing bdd unit-testing ruby-on-rails shoulda
我的应用程序中的某些功能根据客户端的IP地址而有所不同.有没有办法在Rails功能测试中测试?我正在使用Test :: Unit和Shoulda.
Jai*_*yer 31
通过在控制器调用之前更改REMOTE_ADDR环境变量,您可以轻松地执行此操作而无需存根.这是一个虚构的控制器,如果用户的IP地址是1.2.3.4,则将用户重定向到主路径:
def index
if request.remote_ip == '1.2.3.4'
redirect_to root_path
return
end
@articles = Article.all
end
Run Code Online (Sandbox Code Playgroud)
以下是测试它是如何工作的方法:
def test_should_reject_ip_1_2_3_4
@request.env['REMOTE_ADDR'] = '1.2.3.4'
get :index
assert_redirected_to root_path
end
Run Code Online (Sandbox Code Playgroud)
您在控制器调用之前设置了远程IP,因此您可以在没有任何特殊插件或宝石的情况下伪造该数据.而这里是ItemsController的shoulda版本:
context "with ip 1.2.3.4" do
setup do
@request.env['REMOTE_ADDR'] = '1.2.3.4'
get :index
end
should_not_assign_to :items
should_redirect_to("home"){home_path}
should_not_set_the_flash
end
Run Code Online (Sandbox Code Playgroud)