0

我在尝试使用 'should' 和 'factory_girl' 为 Rails 应用程序中的 'create' 创建功能测试时遇到问题。我创建了一个简单的项目,脚手架用户,在 test_helper.rb 中添加了“should”(我系统上的当前 gem 版本 2.11.3)和“factory_girl”。手动创建用户工作正常。以下是重现故障的步骤:

  1. 轨道项目
  2. 脚手架用户名:字符串
  3. 添加 test_helper.rb :

      require 'shoulda'  
      require 'factory_girl'
    
  4. 耙分贝:迁移

  5. 为用户编写以下功能测试(覆盖 users_controller_test.rb ):

    class UsersControllerTest < ActionController::TestCase
     Factory.define(:user) do |u|
      u.name 'joe'
     end
     context "should create user" do
      context "with valid data" do
       setup do
         User.any_instance.expects(:save).returns(true).once
         User.any_instance.stubs(:id).returns(1001)
         post :create, :user => {}
       end
       should_assign_to :user, :class => User
       should_set_the_flash_to "User was successfully created."
       should_redirect_to("user page"){user_path(1001)}
      end
     end
    end
    
  6. 使用“rake test:functionals”运行测试显示失败:

预期的响应是重定向到 ,<http://test.host/users/1001>但重定向到<http://test.host/users>.

我也玩过“should_redirect_to”,因为我看到“should_redirect_to”已被弃用,但没有运气。你有什么想法 ?

先感谢您,

玛丽安·瓦西里·卡莱曼。

4

1 回答 1

0

代替存根User#id,存根User.create并使用特定的用户模拟对象。

setup do
  mock_user = Factory.stub(:user, :id => 1001)
  User.expects(:create).returns(mock_user)
  mock_user.expects(:save).returns(true)
  post :create, :user => {}
end
于 2010-11-11T08:52:50.587 回答