Rspec使用嵌套参数创建帖子

时间:2017-03-17 14:29:46

标签: ruby-on-rails ruby rspec tdd

我正在尝试修复我在评论控制器中编写的一些测试。截至目前,我目前的测试得到了这个错误:

Failure/Error: @outlet = Outlet.find(params[:comment][:outlet_id])

 ActiveRecord::RecordNotFound:
   Couldn't find Outlet with 'id'=

以下是一些测试的示例

describe '#create' do
    context 'with valid attributes' do 
        before :each do
            @outlet = FactoryGirl.create(:outlet)
            @user = FactoryGirl.create(:user)
            @comment_params =  FactoryGirl.attributes_for(:comment)
        end

        let(:create) { post :create, params: { outlet_id: @outlet.id, user_id: @user.id, comment: @comment_params } }

        it "creates new comment" do
            expect { create }.to change { Comment.count }.by(1)
        end

        it "increases the post comment count by 1" do
            expect { create }.to change { @outlet.comments.count }.by(1)
        end

        it "increases user comment count by 1" do
            expect { create }.to change { @user.comments.count }.by(1)
        end
    end
end

我很确定这是因为我的测试中的创建语句

let(:create) { post :create, params: { outlet_id: @outlet.id, user_id: @user.id, comment: @comment_params } }

这是我的评论控制器创建动作

def create
    @outlet = Outlet.find(params[:comment][:outlet_id])
    @comment = @outlet.comments.build(comment_params)
    @comment.user_id = current_user.id


    if @comment.save
        redirect_to(@outlet)
    end
end

我很确定它无法正常工作,因为它正在寻找的outlet_id是comments参数中的嵌套参数。我如何修复我的rspec测试以使其查找嵌套参数?

1 个答案:

答案 0 :(得分:3)

只需将你的参数作为post调用的参数传递,根据需要进行嵌套,例如:

post :create, user_id: @user.id, comment: { outlet_id: @outlet.id }