1

我正在使用 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. '

你能告诉我 - 有什么问题吗?我如何修改测试以使它们正常工作?

UPD:路线看起来不错

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

3 回答 3

5

问题是should_redirect_to现在使用块来评估重定向代码。可悲的是,thoughtbot wiki 和 github 上的自述文件都没有反映这一点,并且仍然包含旧示例。

正确的代码是

should_redirect_to "news articles page" { news_articles_path }

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

于 2009-08-03T11:55:40.787 回答
1

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

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

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

于 2009-07-29T09:19:34.687 回答
1

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

should_redirect_to("news articles page") { news_articles_path }

另请参阅http://dev.thoughtbot.com/shoulda/classes/Shoulda/ActionController/Macros.html#M000015上的新手册

于 2009-08-11T13:54:15.580 回答