Rspec 难以使用构建控制器方法测试#create

Rspec having difficulty testing #create with build controller method

因此,如果您的#create 控制器方法很简单:

@testimonial = Testimonial.new(testimonial_params)

然后你在你的规范中像这样测试它:

testimonials_controller_spec.rb

describe "POST #create" do 
    context "with VALID attributes" do 
        it "creates new testimonial" do 
            expect {
                    post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
            }.to change(Testimonial, :count).by(1)
        end
    end
end

它工作正常。代码:

post :create, testimonial: FactoryGirl.attributes_for(:testimonial)

正确。

然而,在我的 TestimonialsController 中,我的创建方法实际上是:

@testimonial = current_user.testimonials.build(testimonial_params)

我的 rspec 方法不适用于此。我应该用什么代替:

post :create, testimonial: FactoryGirl.attributes_for(:testimonial)

?

Build 不会save/persist 将记录写入数据库。为什么不成功:

@testimonial = current_user.testimonials.new(testimonial_params)
@testimonial.save

在调用控制器操作之前先登录用户。请查找以下内容:

#testimonials_controller_spec.rb 
require 'rails_helper' 
describe TestimonialsController, type: :controller do

  let(:user) do
    FactoryGirl.create :user
  end

  before do
    sign_in user
  end

  describe "POST #create" do 
    context "with VALID attributes" do 
      it "creates new testimonial" do 
        expect {
          post :create, testimonial:    FactoryGirl.attributes_for(:testimonial)
        }.to change(Testimonial, :count).by(1)
      end
    end
  end
end