RSpec:如何测试实例变量

时间:2016-01-21 10:32:33

标签: ruby-on-rails ruby rspec

如何在 UsersController中测试@comments,@ sell_items实例变量:

def show
    @comments = @user.comments.hash_tree
    @comment = @user.comments.build(parent_id: params[:parent_id])
    @seller_items = User.seller_list(current_user)
  end

部分RSpec 测试:

    context "User logged in" do 
      let(:user) { create(:user) }
      let(:user2) { create(:user) }
      let(:comment) { create(:comment, user: user) }

      before { sign_in(user) }

      describe "GET #show" do 
        it "assigns @user" do
          get :show, id: user
          expect(assigns(:user)).to eq(user)
        end

        it "assigns new comment" do 
          get :show, id: user
          expect(assigns(:comment)).to be_instance_of(Comment)
        end

        it "redirect_to :show view" do
            get :show, id: user
            expect(response).to render_template :show
        end
      end
     end

1 个答案:

答案 0 :(得分:2)

您可以测试persistenceassignment

<强>持久性:

此测试将检查实例变量是否保留在整个路径中,以便通过响应使用。

实施例

it "should persists @user" do
  get :show, id: user
  expect(assigns(:user)).to be_persisted
end

<强>分配:

此测试将检查是否为每个实例变量分配了正确/预期的值。

实施例

上面的内容是检查作业的测试示例。

it "should persists @user" do
  get :show, id: user
  expect(assigns(:user)).to eq(user)
end