简体   繁体   English

Rails控制器中的功能测试重定向

[英]Functional testing redirection in a Rails controller

I'm trying to make it so when a model is created via created action it redirects to its show action. 我正在尝试使其通过创建的动作创建模型时将其重定向到其show动作。 That part works fine, but I can't get my functional test to behave. 那部分工作正常,但是我无法执行功能测试。 These tests have been modified from what the scaffold provides. 这些测试已从脚手架提供的内容进行了修改。

  def setup
    @thing = Factory(:thing)
    assert(@thing.id, "Virtual fixture not valid.")
  end

  def test_create_valid
    Thing.any_instance.stubs(:valid?).returns(true)
    post :create
    assert_redirected_to @thing
  end

I'm using factory_girl in setup. 我在安装程序中使用factory_girl。 When I run my tests I get this: 当我运行测试时,我得到以下信息:

Expected response to be a redirect to http://test.host/thing/2 but was a redirect to http://test.host/thing/3 . 预期的响应是重定向到http://test.host/thing/2,但重定向到http://test.host/thing/3

I've done something very similar with my update action in this controller and the test looks the same, but it works. 我在此控制器中执行了与更新操作非常相似的操作,并且测试看起来相同,但是可以正常工作。 I'm a little confused as to what's going on. 我对发生的事情有些困惑。

Edit : Maximiliano points out below that this is probably because this creates a new record in the database, so it redirects to that one. 编辑 :Maximiliano在下面指出,这可能是因为这在数据库中创建了一条新记录,因此将其重定向到该记录。 How can I find the new record just created with the create post request? 如何找到通过创建发布请求刚创建的新记录?

Figured it out with the help of Max (thannks!) To get the object that is created in the database I have to use assigns(): 在Max(感谢!)的帮助下弄清楚了它,要获取在数据库中创建的对象,我必须使用assigns():

assert_redirected_to assigns(:thing) assert_redirected_to分配(:thing)

DISCLAIMER: (I haven't used factory girl yet... so take with a grain of salt) isn't your factory creating the database record? 免责声明:(我还没有用过工厂女工...所以拿些盐吃)您的工厂不是在创建数据库记录吗? if it's so, you're creating it twice, one time with the factory, another with the controller; 如果是这样,您将创建两次,一次是在工厂,一次是在控制器。 then it's normal that the new record has a different id from the factory one... 那么正常情况下,新记录的ID与工厂的ID不同...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM