如果你的#create controller方法是:
@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)
是正确的。
然而,在我的证词控制器,我的创建方法实际上是:
@testimonial = current_user.testimonials.build(testimonial_params)
我的rspec方法不能处理这个问题。我应该用什么来代替:
post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
?
在调用控制器动作之前登录用户。
#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
Build不会将记录保存/持久化到数据库中。为什么不写呢:
@testimonial = current_user.testimonials.new(testimonial_params)
@testimonial.save