用shoulda和factory_girl测试REST - destroy

时间:2009-07-29 08:20:54

标签: ruby-on-rails unit-testing shoulda factory-bot

我正在使用shoulda和factory_girl开发REST测试。代码

 context "on :delete to :destroy" do
    setup do
      @controller = NewsArticlesController.new
      @request = ActionController::TestRequest.new
      @response = ActionController::TestResponse.new

      @news_article =  Factory.create(:news_article)

    end

    should "destroy new NewsArticle" do
      assert_difference('NewsArticle.count', -1) do
        delete :destroy, :id => @news_article.id
      end
    end

    should_redirect_to news_articles_path
  end

因此我看到了

  1) Error:
test: on :delete to :destroy should redirect to index. (NewsArticlesControllerTest):
ArgumentError: block not supplied
    c:/develop/ruby/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/action_controller/macros.rb:201:in `instance_eval'
    c:/develop/ruby/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/action_controller/macros.rb:201:in `__bind_1248853182_16800
0'
    c:/develop/ruby/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call'
    c:/develop/ruby/lib/ruby/gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: on :delete to :destroy should redirect to index. '

你能告诉我PLZ - 什么是错的以及我如何修改测试以使它们正常工作?

UPD:路线看起来不错

news_articles GET    /news(.:format)                    {:controller=>"news_articles", :action=>"index"}

3 个答案:

答案 0 :(得分:5)

问题在于should_redirect_to,它现在使用块来评估重定向代码。可悲的是,无论是思想维基程序还是github上的自述文件都没有反映这一点,仍然包含旧的例子。

正确的代码是

should_redirect_to "news articles page" { news_articles_path }

其中第一个参数只是用于生成测试名称的文本描述(它不像旧版本那样被评估),因此您将获得一个测试名称,如'应该重定向到新闻文章页面'

答案 1 :(得分:1)

也许你应该在调用delete时使用符号和post方法:

 assert_difference 'Article.count', -1 do
    post :delete, :id => ...
  end

(引自http://api.rubyonrails.org/classes/ActiveSupport/Testing/Assertions.html#M001427

答案 2 :(得分:1)

tkramar解决方案指向正确的方向,但我必须将代码编写为:

should_redirect_to("news articles page") { news_articles_path }

另请参阅http://dev.thoughtbot.com/shoulda/classes/Shoulda/ActionController/Macros.html#M000015

上的新手册