【问题标题】:Rails Controller testingRails 控制器测试
【发布时间】:2014-10-31 02:25:40
【问题描述】:

我正在为测试程序做thoughtbot 介绍。我不知道如何测试他们想要什么。

以下是我的测试。

require "rails_helper"

describe PeopleController do
  describe "#create" do
    context "when person is valid" do
      it "redirects to #show" do

        post :create, FactoryGirl.build_stubbed(:person)

        expect(response).to redirect_to(show_people_path)
      end
    end

    context "when person is invalid" do
      it "redirects to #new" do
        pending "create this test"
      end
    end
  end
end

我当然用的是工厂女孩。我尝试了几种方法。我真的不知道如何测试这个控制器。

任何见解都会很棒。

【问题讨论】:

    标签: ruby-on-rails rspec tdd


    【解决方案1】:

    我会使用 FactoryGirl 创建一个“无效”人员,并将其作为参数发送到 post :create

    要创建无效人员记录,为什么不在 FactoryGirl 中使用nested factories?根据模型中的验证,您可以简单地执行以下操作:

    spec/factories/person.rb

    FactoryGirl.define do 
      factory :person do
        ...
        factory :invalid_person do
          ...
          email nil
          ...
        end
      end
    end
    

    在您的测试中

    context "when person is invalid" do
      it "redirects to #new" do
        post :create, FactoryGirl.build_stubbed(:invalid_person)
        expect(response).to redirect_to action: :new
      end
    end
    

    【讨论】:

    • 谢谢。这现在更有意义了。但是我的终端抛出了一个未初始化的常量 FactoryGirl 错误...... hrm ..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多