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

时间:2015-05-23 14:46:30

标签: ruby-on-rails ruby rspec

因此,如果您的#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)

2 个答案:

答案 0 :(得分:3)

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

#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

答案 1 :(得分:-1)

Build不会将记录保存/保存到数据库中。为什么不成功:

readline()