0

我有两个模型:UserTopic. 用户可以有多个主题,主题属于一个用户。

在我的主题控制器中,我正在尝试测试有效主题的创建操作:

考试

  # topics_controller.test.rb
  def test_create_valid
    sign_in Factory(:user) # Devise will redirect you to the login page otherwise.
    topic = Factory.build :topic
    post :create, :topic => topic
    assert_redirected_to topic_path(assigns(:topic))
  end

工厂(工厂女孩)

# factories.rb
Factory.define :user do |f|
  f.sequence(:username) { |n| "foo#{n}"}
  f.password "password"
  f.password_confirmation { |u| u.password}
  f.sequence(:email) { |n| "foo#{n}@example.com"}
end

Factory.define :topic do |f|
  f.name "test topic"
  f.association :creator, :factory => :user
end

测试输出

ERROR test_create_valid (0.59s) 
      ActionController::RoutingError: No route matches {:action=>"show", :controller=>"topics", :id=>#<Topic id: nil, name: nil, created_at: nil, updated_at: nil, creator_id: 1>}
      /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.7/lib/action_dispatch/routing/route_set.rb:425:in `raise_routing_error'

在测试中,topic.valid?为真且topic.name具有出厂值。

但是,该帖子似乎并没有过去post :create, :topic => topic。看起来它从未保存在数据库中,因为它甚至在测试输出中都没有 id。

编辑:即使我为新主题绕过工厂,它也不起作用。

  def test_create_valid
    @user = Factory :user
    sign_in @user
    topic = @user.topics.build(:name => "Valid name.")
    post :create, :topic => topic
    assert_redirected_to topic_path(assigns(:topic))
  end

导致相同的测试错误。

4

2 回答 2

1

这里的post方法需要参数作为第二个参数,而不是对象。这是因为create控制器中的操作将使用params方法来检索这些参数并在创建新主题的过程中使用它们,使用如下代码:

Topic.new(params[:topic])

因此,您params[:topic]需要成为您要创建的项目的属性,而不是现有Topic对象。但是,您可以使用Factory.build :topic获取实例化Topic对象,然后执行此操作以使其工作:

post :create, :topic => topic.attributes
于 2011-05-08T02:34:44.427 回答
0

这远远超出了我的范围,但我显然不得不手动设置post :create参数中的属性。:topic => topic鉴于这是一个 Rails 习语,这似乎很违反直觉。

  def test_create_valid
    sign_in @user
    topic = Factory.build :topic
    post :create, :topic => {:name => topic.name}
    assert_redirected_to topic_path(assigns(:topic))
  end

希望有人可以阐明为什么post :create, :topic => topic不起作用。

于 2011-05-08T02:25:42.923 回答