如何将其他数据传递给测试?

时间:2015-07-05 10:10:26

标签: ruby-on-rails ruby-on-rails-4 testing functional-testing

请帮助解决问题。

控制器标签:

class TagsController < ApplicationController
  def show
    @tag = Tag.find(params[:id])
    @posts = @tag.posts
  end
end

测试标签:

class TagsControllerTest < ActionController::TestCase
  fixtures :tags, :posts

  setup do
    @tag = tags(:one)        
  end

  test "should get show" do
    get :show, :tag => @tag
    assert_response :success
    assert_not_nil assigns(:tag)
    assert_template :show
    assert_template layout: "layouts/application"        
  end    

  test "should route to show tag posts" do
    assert_generates "/tags/@tag", controller: 'tags', action: 'show', id: "@tag"  # OK
  end  
end

灯具标签:

one: 
  tagname: 'qwe'

灯具帖子:

one:
  title: 'MyString1'
  body: '1Lorem Ipsum'
  user: :one
  views: 2

开始测试后,我收到以下错误消息:

  1) Error:
TagsControllerTest#test_should_get_show:
ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"tags", :tag=>"980190962"}
    test/controllers/tags_controller_test.rb:20:in `block in <class:TagsControllerTest>'

请告诉我如何在测试中传递@posts。或告诉我另一种解决方案

模型标签和帖子通过HABTM链接

2 个答案:

答案 0 :(得分:2)

更改此行:

get :show, :tag => @tag

get :show, id: @tag.id

答案 1 :(得分:2)

您的测试用例应该通过:id而不是:tag。它应该看起来像:

  test "should get show" do
    get :show, :id => @tag.id
    assert_response :success
    assert_not_nil assigns(:tag)
    assert_template :show
    assert_template layout: "layouts/application"        
  end